IO programming file read/write Open file
open(file, mode=‘r‘, buffering=None, encoding=None, errors=None, newline=None, closefd=True)
To see the API in particular, here are just a few common methods.
The file name of the Open function is a required parameter, which returns a Document object
#打开一个文件。f = open(‘read.txt‘, ‘r‘)
of the Open function
ModeParameters:
value |
function Description |
' R ' |
Read mode |
' W ' |
Write mode |
A |
Append mode |
' B ' |
Binary mode |
+ |
Read/write mode |
b parameter when processing a text file is less than the B parameter, but processing other types of files (binary files,) such as MP3 or images, then should be added in the schema parameter B
Buffering, File buffer:
Buffer, the default is no buffer,
If the parameter is 0,io operation is no buffer, write data directly on the hard disk,
If the parameter is a 1,io operation is buffered, the data is written into memory, only the use of the flush function, or the close function, the data will be updated to the hard disk,
- If the argument is greater than days, it indicates the size of the buffer (in bytes), 1 (or any negative number) that represents the size of the default buffer used.
File reads,
File reads are mainly divided into bytes read and read by line, commonly used methods are read (), ReadLines (), Close ()
If the text file is opened successfully, the next call to the Read () method is to write the contents of the file all in memory at once, and finally return the object of type str:
F.read ()
- Call Close () to close a reference to a file that must be closed after it is used, because the file object consumes system resources and affects system IO operations.
The following close () method will not be called when an IO exception occurs because of an IO exception in the file operation. So in order to ensure the robustness of the program, we need to use try...finally to achieve.
try: f = open(‘read.txt‘, ‘r‘) print(f.read())finally: if f: f.close()
Python provides a simple way to use the WITH statement instead of the try...finally code block and the Close () method.
with open(‘read.txt‘, ‘r‘) as fileReader: print(fileReader.read())
Due to the possibility of large files, there will be insufficient memory, Python provides a more reasonable way to call ReadLine () to read a line of content each time.
- Small files can be read directly into memory by taking the read () method.
- A more secure way to make large files is to use read (size) continuously
- For text files such as configuration files, it is more reasonable to use ReadLine ().
with open(‘read.txt‘, ‘r‘) as fileReader: for line in fileReader.readlines(): print(line.strip())得到结果:123456789
File Write
Recommended wording:
with open(‘read.txt‘, ‘w‘) as fileWriter: for num in range(1, 100): fileWriter.write(str(num)+‘\n‘)
The IO operation of the Python Advanced trilogy