当前位置:网站首页>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 .
边栏推荐
- (13) Simple temperature alarm device based on 51 single chip microcomputer
- Js继承方法
- KEGG通路的从属/注释信息如何获取
- 一年涨薪三次背后的秘密
- Argocd Web UI loading is slow? A trick to teach you to solve
- Customer first | domestic Bi leader, smart software completes round C financing
- 图片批处理|必备小技能
- Why setting application.targetframerate doesn't work
- 解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
- Explain cache consistency and memory barrier
猜你喜欢

Overview of head pose estimation

KEGG通路的从属/注释信息如何获取

Flink Window&Time 原理

MDM数据质量应用说明

Eight ways to solve EMC and EMI conducted interference

The five pictures tell you: why is there such a big gap between people in the workplace?

Huid learning 7: Hudi and Flink integration

Ciou loss

Source code analysis of linkedblockingqueue

XMIND Zen installation tutorial
随机推荐
台大林轩田《机器学习基石》习题解答和代码实现 | 【你值得拥有】
Detailed explanation of the basic use of express, body parse and express art template modules (use, route, path matching, response method, managed static files, official website)
TXT文本文件存储
SQL server time field sorting
Customer first | domestic Bi leader, smart software completes round C financing
When I use MySQL CDC, there are 100 million pieces of data in the source table. In the full volume phase, when I synchronize 10 million, I stop, and then pass
Div tags and span Tags
Do you know the five minute rule and the ten byte rule?
How to configure phpunit under window
Data analysis interview question summary
'global event bus' &' message subscription and Publishing '
Basic syntax of jquey
Business digitalization is running rapidly, and management digitalization urgently needs to start
Kubernetes cluster configuration dashboard service
Recycling of classes loaded by classloader
mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
图片批处理|必备小技能
Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
创建线程的3种方式
Opengauss synchronization status query