当前位置:网站首页>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 .
边栏推荐
- Three ways to create threads
- 我来教你如何组装一个注册中心?
- Go panic and recover
- Hcip day 9_ BGP experiment
- Go synergy
- PostgreSQL: cannot change the type of column used by a view or rule
- Top all major platforms, 22 versions of interview core knowledge analysis notes, strong on the list
- Div tags and span Tags
- 图片批处理|必备小技能
- Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
猜你喜欢

Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology

Gb/t 41479-2022 information security technology network data processing security requirements map overview

Ciou loss

ciou损失

Dry goods semantic web, Web3.0, Web3, metauniverse, these concepts are still confused? (top)

CSV文件存储

Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
![[soft test software evaluator] 2013 comprehensive knowledge over the years](/img/c5/183acabd7015a5e515b7d83c127b2c.jpg)
[soft test software evaluator] 2013 comprehensive knowledge over the years

Leetcode brushes questions. I recommend this video of the sister Xueba at station B

HCIP第八天
随机推荐
象棋机器人夹伤7岁男孩手指,软件测试工程师的锅?我笑了。。。
I am a 27 year old technical manager, whose income is too high, and my heart is in a panic
Why is the text box of Google material design not used?
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
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
JS inheritance method
Let me teach you how to assemble a registration center?
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]
Flink window & time principle
How to configure phpunit under window
Completion report of communication software development and Application
A new method of exposing services in kubernetes clusters
站在大佬的肩膀上,你可以看的更远
【软考软件评测师】2013综合知识历年真题
NDK series (6): let's talk about the way and time to register JNI functions
Solution: indexerror: index 13 is out of bounds for dimension 0 with size 13
Competition: diabetes genetic risk detection challenge (iFLYTEK)
Line generation (matrix)
mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
Baidu AI Cloud Jiuzhou district and county brain, depicting a new blueprint for urban and rural areas!