A. Read-write mode
For read-write mode, must be read before write, because the default cursor position at the beginning, when finished it again for writing. We'll use the highest frequency mode is r +
r + mode
Look correct operation:
f1 = open('../path1/小娃娃.txt',mode='r+',encoding='utf-8')
msg = f1.read()
f1.write('这支烟灭了以后')
f1.flush()
f1.close()
print(msg)
结果:
正常的读取之后,写在结尾
Look wrong operation:
f1 = open('../path1/小娃娃.txt',mode='r+',encoding='utf-8')
f1.write('小鬼')
msg = f1.read()
f1.flush()
f1.close()
print(msg)
结果:
这样写会把小鬼写在开头,并且读出来的是小鬼之后的内容
r + mode must remember is read before write
r + mode pits
In the operation mode, if r + content read regardless of how to read the contents of the cursor is displayed or how many rewriting operations when documents are carried out at the end: Note pit.....
II. Write Read Mode
First of all empty the contents, then write the last read, but read content is empty, not used
f1 = open('../path1/小娃娃.txt',mode='w+',encoding='utf-8')
f1.write('小鬼')
msg = f1.read()
f1.flush()
f1.close()
print(msg)
It is said that the first reading in writing and not on the fact .w + w mode under the same mode, the file emptied, the contents written.
Additional read (a +, a + b)
a + mode, whether it is read or after the first reading, the data are not read
f = open('../path1/小娃娃.txt',mode='a+',encoding='utf-8')
f.write('阿刁')
f.flush()
msg = f.read()
f.close()
print(msg)