当前位置:网站首页>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 .
边栏推荐
- NPM and yarn use (official website, installation, command line, uploading your own package, detailed explanation of package version number, updating and uninstalling package, viewing all versions, equ
- Go waitgroup and defer
- Principle of line of sight tracking and explanation of the paper
- Hundreds of billions of it operation and maintenance market has come to the era of speaking by "effect"
- ES查询索引字段的分词结果
- 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
- [activity registration] User Group Xi'an - empowering enterprise growth with modern data architecture
- Among China's top ten national snacks, it is actually the first
- KEGG通路的从属/注释信息如何获取
- I use SqlClient normally, and dlink submission will report this error. What should I do?
猜你喜欢

置顶各大平台,22版面试核心知识解析笔记,强势上榜

Round C financing has been completed! Smart software leads domestic Bi ecological empowerment, and products and services are a step forward

Let me teach you how to assemble a registration center?

Huid learning 7: Hudi and Flink integration

一年涨薪三次背后的秘密

Do you know the five minute rule and the ten byte rule?

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

Path and attribute labels of picture labels

GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览

MDM数据质量应用说明
随机推荐
Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
C #, introductory tutorial -- debugging skills and logical error probe technology and source code when the program is running
Digital signatures and Ca certificates
图片批处理|必备小技能
Eight ways to solve EMC and EMI conducted interference
Alibaba technology has four sides + intersection +hr, and successfully got the offer. Can't double non undergraduate students enter the big factory?
Hcip day 9_ BGP experiment
Centralized log management with sentry
Go panic and recover
Hcip day 8
mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
[advanced drawing of single cell] 07. Display of KEGG enrichment results
Service current limiting and fusing of micro service architecture Sentinel
NPM and yarn use (official website, installation, command line, uploading your own package, detailed explanation of package version number, updating and uninstalling package, viewing all versions, equ
Ciou loss
Completion report of communication software development and Application
Uniapp ---- detailed steps to obtain the longitude and latitude of the current position and other information (including applet)
PostgreSQL: cannot change the type of column used by a view or rule
Wechat applet - wechat applet browsing PDF files
SQL injection - pre Foundation