Introduction to using Python open of file processing

  • 2020-04-02 14:27:23
  • OfStack

1. The open () syntax

Open (file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]])
The open function has many arguments, most commonly file, mode, and encoding
The file File location, need to be quoted
mode File open mode, see 3 below
The buffering Can be 0,1, > 1 three, 0 for buffer closed (for binary mode only), 1 for line buffer (for text mode only), > 1 represents the size of the buffer initialized;
encoding Represents the encoding of the returned data, generally utf8 or GBK;
The errors The value of is generally strict, ignore, when taking strict, when there is a problem with the character encoding, it will report an error, when taking ignore, there is a problem with the encoding, the program will ignore, continue to execute the following program.
newline The available values are None, \n, \r, ", '\r\n', used to distinguish newline characters, but this parameter is only valid for text mode;
closefd Values, it is related to the incoming file parameters, by default is True, the incoming filename for the file, the file parameter value to False, the file is the file descriptor, what is the file descriptor, and is a non-negative integer, in the Unix kernel system, open a file, will return a file descriptor.

2. File () versus open() in Python
Both can open and manipulate files, and both have similar usages and parameters, but the two ways of opening files are fundamentally different. File is a file class , use file() to open the file , which is equivalent to constructing the file class, and opening the file with open(), which is equivalent to Python's built-in functions operate Open is recommended

3. Basic value of parameter mode

Character Meaning
' r' open for reading (default)
' w' open for writing, truncating the file first
' a' open for writing, appending to the end of the file if it exists
' b' binary mode
' t' text mode (default)
' +' open a disk file for updating (reading and writing)
' U' universal newline mode (for backwards compatibility; should not be used in new code)

R, w and a are the basic modes of opening files, corresponding to read-only, write-only and append modes;
B, t, +, U, these four characters, and the above file open mode combination, binary mode, text mode, read and write mode, general newline character, according to the actual situation combination,

Common mode value combinations


r or rt  Default mode, text mode read 
rb    Binary file 
 
w or wt  Text mode write, file storage is cleared before opening 
wb   Binary write, file store is also cleared 
 
a   Append mode, can only be written at the end of the file 
a+  In read-write mode, writes can only be written at the end of the file 
 
w+  Read-write, and a+ The difference is to empty the file contents 
r+  Read-write, and a+ The difference is that you can write to the file anywhere 

4. Test
Test.txt, as follows:


Hello,Python
www.jb51.net
This is a test file

Use a small piece of code to test the write file to visually show the difference


test = [ "test1n", "test2n", "test3n" ]
f = open("test.txt", "a+")
try:
 #f.seek(0)
 for l in test:
  f.write(l)
finally:
 f.close()

The difference between a+, w+ and r+ modes (restore test.txt after test)
A + model


# cat test.txt
Hello, Python
www.jb51.net
This is a test file
test1
test2
test3

W + model


# cat test.txt
test1
test2
test3

R + model
Before we write to the file, we add an f. eek(0) in the above code to locate the write location (at the beginning of the file) and directly overwrite the number of characters (note: n is also one character).


# cat test.txt
test1
test2
test3
inuxeye.com
This is a test file

Note: when a file is opened in r+ mode, it must exist, otherwise an error is reported, as is the case with 'r' mode
Other tests


>>> f = open('test.txt')
>>> f.read() # Read the entire file, string display 
'Hello,Pythonnwww.jb51.netnThis is a test filen'
>>> f.read() # The pointer is at the end of the file and can no longer read the contents 
''

>>> f = open('test.txt')
>>> f.readline() # Read one line at a time with the pointer at the end of the line 
'Hello,Pythonn'
>>> f.tell() # The character length of the changed line 
13
>>> f.readline()
'www.jb51.netn'
>>> f.tell()
30
>>> f.readline()
'This is a test filen'
>>> f.tell()
50
>>> f.readline()
''
>>> f.tell() # The pointer stops on the last line 
50

>>> f = open('test.txt')
>>> f.readlines() # Read the entire file and display it as a list 
['Hello,Pythonn', 'www.jb51.netn', 'This is a test filen']
>>> f.tell() # The pointer is on the last line 
50

>>> f = open('test.txt','w') # Overwrite to create a new file 
>>> f.write('Hello,Python!') # If the write is less than 1024 , there will be memory, otherwise need to refresh 
>>> f.flush() # Write to hard disk 
>>> f.close() # Closing the file will automatically refresh 
>>> f.write('Hello,Linuxeye') # After closing, the write fails, indicating that the file is closed 
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file 

Related articles: