The common patterns for opening files are:
- R, read-only mode "default"
- W, write-only mode "unreadable; not exist" created; empty content;
- A, append mode "readable; not present, create; append content only;"
"+" means you can read and write a file at the same time
- r+, read and write "readable, can write" "can be understood as read before writing, do not erase the original file content, the pointer in 0"
- w+, write read "Readable, can write" "can be understood as read first, erase the original file content, the pointer in 0"
- A +, write read "Readable, can write" "does not erase the original file content, but the pointer directly to the last, read the original content first reset the pointer"
Mode |
can do operation |
If the file does not exist |
whether to overwrite |
pointer position |
R |
Read Only |
Error |
- |
0 |
r+ |
Readable and writable |
Error |
Whether |
0 |
W |
can only write |
Create |
Is |
0 |
w+ |
can be written and readable |
Create |
Is |
0 |
A |
can only write |
Create |
No, append write |
At last |
A + |
Readable and writable |
Create |
No, append write |
At last |
You can make a test file, modify the next open mode, and then output look at the pointer difference
f=open(‘I:\\python\\test\\text.txt‘,‘r+‘)print(‘指针在:‘,f.tell())lines=f.read()if f.writable(): f.write(‘nono\n‘)else: print("此模式不可写")print(‘指针在:‘,f.tell())f.close()
A + mode, although can read, but the pointer is to the end, direct read, will not be content, you can use Seek () to reset the pointer
f=open(‘I:\\python\\test\\text.txt‘,‘a+‘)print(‘指针在:‘,f.tell())lines=f.read()print(‘文件内容是:‘,lines) #输出为空print(‘seek 0‘)f.seek(0)print(‘指针在:‘,f.tell())lines=f.read()print(‘文件内容是:‘,lines)if f.writable(): f.write(‘nono\n‘)else: print("此模式不可写")print(‘指针在:‘,f.tell())f.close()
Python file operation differences in read, write, append