当前位置:网站首页>TXT text file storage
TXT text file storage
2022-07-28 09:00:00 【W_ chuanqi】
Personal profile
Author's brief introduction : Hello everyone , I am a W_chuanqi, A programming enthusiast
Personal home page :W_chaunqi
Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
May you and I share :“ If you are in the mire , The heart is also in the mire , Then all eyes are muddy ; If you are in the mire , And I miss Kun Peng , Then you can see 90000 miles of heaven and earth .”

List of articles
TXT Text file storage
Save the data as TXT The operation of text is very simple , and TXT Text is compatible with almost any platform , But there is also a disadvantage , Is not conducive to retrieval . So if the requirements for retrieval and data structure are not high , The pursuit of convenience first , You can use TXT This storage .
Let's take a look at using Python preservation TXT Method of text file .
1. Instance Introduction
We use the movie example website https://ssr1.scrape.center/ For example , Crawl to the home page 10 Data of the film , Then store the relevant information as TXT Text format .
The example code is as follows :
import requests
from pyquery import PyQuery as pq
import re
url = 'https://ssr1.scrape.center/'
html = requests.get(url).text
doc = pq(html)
items = doc('.el-card').items()
file = open('movies.txt', 'w', encoding='utf-8')
for item in items:
# The movie name
name = item.find('a > h2').text()
file.write(f' name :{
name}\n')
# Category
categories = [item.text()
for item in item.find('.categories button span').items()]
file.write(f' Category :{
categories}\n')
# Release time
published_at = item.find('.info:contains( release )').text()
published_at = re.search('(\d{4}-\d{2}-\d{2})', published_at). group(
1) if published_at and re.search('\d{4}-\d{2} -\d{2}', published_at) else None
file.write(f' Release time :{
published_at}\n')
# score
score = item.find('p.score').text()
file.write(f' score :{
score}\n')
file.write(f'{
"="*50}\n')
file.close() # here close Want to be with for At the same level , If in for Internal error reporting
The purpose here is mainly to demonstrate the storage method of files , So it's not necessary requests Exception handling part . First , use requests To extract the homepage of the website HTML Code , And then use it pyquery The parsing library converts the name of the movie 、 Category 、 Release time 、 Extract the scoring information .
utilize Python Provided open Method to open a text file , Get a file operation object , Here it is assigned as file, Each part of the information extracted , using file Object's write Method to write this information to the file .
After all extraction , call close Methods will file Object closed , In this way, the content of the website home page is successfully written into the text .
Run the program , It can be found that a movies.txt file , Its contents are shown in the figure .

It can be seen that , The content of the movie information has been saved in text form .
Let's look back at what we need to know in this section , That is, text writing , In fact, that is open、write、close The usage of these three methods .
open The first parameter of the method is the name of the target file to be saved ; The second parameter represents how the data is written to the text , Here is w, Indicates that... Is written in an overwritten manner ; The third parameter specifies the file code as utf-8. Last , After writing , You also need to call close Method to close the file object .
2. Open mode
In the example just now ,open The second parameter of the method is set to w, In this way, the source file will be emptied every time text is written , Then write the new content to the file .w It's just a way to open files , The following is a brief introduction to several other .
r: Open a file as read-only , It means that you can only read the contents of the file , It cannot be written . This is also the default mode .
rb: Open a file in binary read-only mode , Usually used to open binary files , For example, audio 、 picture 、 Video etc. .
r+: Open a file read-write , You can read and write files .
rb+: Open a file in binary read-write mode , You can also read and write , Just read and write binary data .
w: Open a file by writing . If the file already exists , Then cover it . If the file does not exist , Create a new file .
wb: Open a file by binary writing . If the file already exists , Then cover it . If the file does not exist , Create a new file .
w+: Open a file read-write . If the file already exists , Then cover it . If the file does not exist , Create a new file .
wb+: Open a file in binary read-write format . If the file already exists , Then cover it . If the file does not exist , Create a new file .
a: Open a file in append mode . If the file already exists , Then the file pointer will be placed at the end of the file . in other words , New content will be written after existing content . If the file does not exist , Create a new file to write .
ab: Open a file by binary append . If the file already exists , Then the file pointer will be placed at the end of the file . in other words , New content will be written after existing content . If the file does not exist , Create a new file to write .
That is to say , New content will be written after existing content . If the file does not exist , Create a new file to write .
a+: Open a file read-write . If the file already exists , Then the file pointer will be placed at the end of the file . Append mode when the file opens . If the file does not exist , Create a new file for reading and writing .
ab+: Open a file by binary append . If the file already exists , Then the file pointer will be placed at the end of the file , If the file does not exist , Create a new file for reading and writing .
3. Simplify writing
There is another shorthand for file writing , Is the use of with as grammar . When with At the end of the control block , The file will close automatically , It means that there is no need to call close Method .
This storage method can be abbreviated as follows :
with open('movies.txt', 'w', encoding-'utf-8') as file:
file.write(f' name :{
name}\n')
file.write(f' Category : {
categories}\n')
file.write(f' Release time : {
published_at}\n')
file.write(f' score :{
score}\n')
The above is the use of Python Save results as TXT Method of file , This method is simple and easy to use 、 Efficient operation , Is one of the most basic data storage methods .
边栏推荐
- Flink window & time principle
- Slice function of JS handwriting function (thoroughly understand the header but not the footer)
- [soft test software evaluator] 2013 comprehensive knowledge over the years
- PHP Basics - PHP uses PDO
- oracle sql 问题
- Data fabric, next air outlet?
- Review the past and know the new MySQL isolation level
- Hundreds of billions of it operation and maintenance market has come to the era of speaking by "effect"
- 创建线程的3种方式
- Div tags and span Tags
猜你喜欢

Business digitalization is running rapidly, and management digitalization urgently needs to start

看得清比走得快更重要,因为走得对才能走得远
![Vrrp+mstp configuration details [Huawei ENSP experiment]](/img/44/987e9ff87f5c8e2a2ab493e947f884.png)
Vrrp+mstp configuration details [Huawei ENSP experiment]

49 opencv deep analysis profile

When will brain like intelligence, which is popular in academia, land? Let's listen to what the industry masters say - qubits, colliders, x-knowledge Technology

Argocd Web UI loading is slow? A trick to teach you to solve

Chapter 2-14 sum integer segments

mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库

Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice

Eight ways to solve EMC and EMI conducted interference
随机推荐
Chapter 2-14 sum integer segments
[cloud computing] several mistakes that enterprises need to avoid after going to the cloud
阿里技术四面+交叉面+HR面,成功拿到offer,双非本科进不了大厂?
A new method of exposing services in kubernetes clusters
Div tags and span Tags
谷歌 Material Design 的文本框为什么没人用?
PHP Basics - PHP uses PDO
图片批处理|必备小技能
[soft test software evaluator] 2013 comprehensive knowledge over the years
Bluetooth technology | it is reported that apple, meta and other manufacturers will promote new wearable devices, and Bluetooth will help the development of intelligent wearable devices
Two dimensional array and operation
一年涨薪三次背后的秘密
Argocd Web UI loading is slow? A trick to teach you to solve
Hcip day 8
HCIP第九天_BGP实验
Win the bid! Nantah general gbase 8s won the bid for the 2022 database framework project of NARI Group
Basic syntax of jquey
Chapter 2-2 calculation of piecewise function [1]
第2章-2 计算分段函数[1]
How to import and export Youxuan database