# The following are operating under normal open files
First, a list of grid
mode | Do operations | If the file does not exist | Overwrite |
r | Only read | An error | --- |
r+ | Read and write | An error | Yes |
w | Only write | create | Yes |
w+ | Read and write | create | Yes |
a | Only write | create | No, additional |
a+ | Read and write | create | No, additional |
b | ----- (binary read mode) | --------- (with the use of read and write) | ----- |
In fact, here's a good read to understand, but for a and a +, they are added to the text (Here we note that cover lid is not covered duplicate content, but covers the entire contents ) ------ file is rewritten (back files, ha ha ha)
Plus without b depend on the form of text files
2.1 write files plus read the file
# Is not added, but will be covered before each write (will cover any field,) # with Open ( 'name.txt', 'W', encoding = 'UTF8') AS F: # f.writelines ( "0001" + '\ n' + 'Bob' + '\ n' + ' 1701 class') # with open('name.txt','r',encoding='utf8')as f: # for line in f.readlines(): # print(line,end='')
# The readlines () reads a plurality of rows, there is no difference between s and s, # with Open ( 'demo2.txt', 'R & lt', encoding = 'UTF8') AS F: # for Line in f.readlines (): # Print (Line, End = '')
2.2 file additional written
文件读取 # with open('demo.txt','r',encoding='utf8')as f: # for line in f.readlines(): # print(line,end='') # #文件追加写入 # with open('demo.txt','a+',encoding='utf8')as f: # f.write('\n') # f.write('you are a boy!')
2.3 binary read (explain briefly)
Read file read file operations, read the documents until the terminator (EOF) is considered to read the final document, Python would think byte \ x1A (26) is converted into a character for the document terminator (EOF),
Therefore, when using the 'r' for reading a binary file, reads the document may appear incomplete phenomenon.
Example:
Binary file there is arranged in the high-low data: 7F 32 1A 2F 3D 2C 12 2E 76
if 'r' is read, then read the third byte, i.e. that end of the file.
If 'rb' read in binary bits, the read byte is not converted into characters, thereby avoiding the above error.