posted on 2024-11-02 14:20 read(306) comment(0) like(0) collect(2)
Variables save data in memory. If the program is restarted/powered off, the data in memory will be lost.
To achieve persistent storage of data, you need to store the data , which can be stored in the hard disk, that is, in a file.
Some common file types :
文本文件 txt
可执行文件 exe class
图片文件 jpg png
视频文件 mp4 mov
office文件 ppt docx
This article focuses primarily on text files .
There are a lot of files in the system. In order to organize these files more comprehensively, many folders are often used , which are also called directories in Linux
. In fact, a file often has many nested directories. In order to easily determine the location of a file, it is very convenient to use a file path to describe it.
Take the path where I store Python code as an exampleD:\code\python
\
represents a first-level directory. The current Python is placed in the code directory under the D drive.\
or it can be used . It is generally more convenient /
to use when writing code . Absolute path and relative path:/
To use files, you need to save data through files and retrieve the saved data later. In order to read and write files, you must first open the file and close the file after completing the operation.
Use built-in functions open
to open the file.
f = open('d:/test.txt','r')
r
' means opening in read mode, ' w
means opening in write mode, and 'a' means opening in append mode.Use close
method to close an opened file.
f.close()
Remember to close the files you have used.
There is a limit to the number of files a program can open at the same time.
flist = []
count = 0
while True:
f = open('d:/tmp/test.txt','r')
flist.append(f)
count+=1
print(f'count = {count}')
'''
...
count = 8187
count = 8188
count = 8189
Traceback (most recent call last):
File "d:\code\python\python_test1\test.py", line 158, in <module>
OSError: [Errno 24] Too many open files: 'd:/tmp/test.txt'
'''
From the code, it can be seen that a program can open about 8,000 files. If files are opened in a loop without being closed, the above problem will occur. When a program opens more files than the upper limit, an exception will be thrown.
In the above code, a list is used to save all file objects. If it is not saved, Python's built-in garbage collection mechanism will automatically close the file when the file is destroyed.
However, since the garbage collection mechanism is not necessarily timely, we still need to manually recycle when writing code to avoid relying on automatic recycling.
Once the file is open, you can write to it.
open
the second parameter is w
.write
method.f = open('d:/tmp/test.txt','w')
f.write('i am yui')
f.close()
Open test.txt and find that it has been written.
If r
you write in this way, the program will throw an exception.
After
w
successfully opening the file, the data in the original file will be cleared.
Toa
implement appending, the original content remains unchanged and the written content will exist at the end of the previous file content.
f = open('d:/tmp/test.txt','w')
f.write('i am yui')
f.close()
f = open('d:/tmp/test.txt','a')
f.write(',hello')
f.close()
r
opening the file using the method.read
the method to complete the read operation, and the parameters are indicated 读取几个字符
.f = open('d:/tmp/test.txt','r')
result = f.read(10)
print(result)
f.close()
'''
i am yui,h
'''
111111
222222
333333
444444
Let's print the contents of this file.
f = open('d:/tmp/test.txt','r')
for line in f:
print(f'line = {line}')
f.close()
'''
line = 111111
line = 222222
line = 333333
line = 444444
'''
Since there is a line break at the end of each line in the file, a line break will be added by default when printing, so there will appear to be spaces between the printed results
.
print(f'line = {line}',end='')
It can replace the line break that comes with print.
readline
directly read the entire content of the file and return a list with each element being a line.f = open('d:/tmp/test.txt','r')
lines = f.readlines()
print(lines)
f.close()
'''
['111111\n', '222222\n', '333333\n', '444444\n']
'''
When Chinese characters appear in the file content, errors may occur when reading the file content. That is, garbled characters appear.
Why does this happen?
When computers represent Chinese characters, they use a certain encoding method, which is called字符集
The so-called "encoding method" is essentially to use numbers to represent Chinese characters.
As we all know, computers can only represent binary data. If you want to represent English letters, Chinese characters or other text characters, you have to use encoding.
The simplest character encoding ASCII uses a simple integer to represent English letters and numbers, but if you want to represent Chinese characters, you need a larger code table.
The commonly used Chinese character encoding methods are mainly: GBK and UTF-8.
To do this, it is necessary to ensure that the encoding method of the file itself is consistent with the encoding method used to read the file in the Python code to avoid errors.
By default, python3 opens files in the same character set as the system, and the character set of Windows Simplified Chinese version uses GBK, so if the file itself is encoded in GBK, it can be processed correctly. If not, an error will occur.
After opening a file, the easiest thing to forget is closing it. Python provides a context manager to help us close files automatically.
with open('d:/tmp/test.txt','r') as f:
lines = f.readlines()
print(lines)
'''
['111111\n', '222222\n', '333333\n', '444444\n']
'''
Author:Poison
link:http://www.pythonblackhole.com/blog/article/245802/600ca78710d1a918d86a/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!