A write file operation

Write Mode

Write coverage

When writing the file we want to develop a written document to refresh habits. Refresh flush ()

f = open('../path1/小娃娃.txt',mode='w',encoding='utf-8')
f.write('太白很白')
f.flush()
f.close()

结果:
当我选择使用w模式的时候,在打开文件的时候就就会把文件中的所有内容都清空,然后在操作

Note: If the file does not exist mode creates the file using w, w exist schema file is written to cover, when you open the file will file all the contents emptied.

f1 = open('../path1/小娃娃.txt',mode='r',encoding='utf-8')
msg = f1.read()
print(msg)

# 这个是先查看小娃娃文件中有哪些内容


f = open('../path1/小娃娃.txt',mode='w',encoding='utf-8')
f.write('太白很白')
f.flush()
f.close()
# 这个是对小娃娃文件进行覆盖写操作


f1 = open('../path1/小娃娃.txt',mode='r',encoding='utf-8')
msg = f1.read()
print(msg)

# 查看覆盖写后的内容

Attempt to read

f1 = open('../path1/小娃娃.txt',mode='w',encoding='utf-8')
msg = f1.read()
print(msg)

结果:
Traceback (most recent call last):
  File "D:/python_object/path2/test.py", line 563, in <module>
    msg = f1.read() 
io.UnsupportedOperation: not readable    #模式是w,不可以执行读操作

Under wb mode, you may not be specified to open the file editing, but the time to write the file must be converted into a string of bytes of data utf-8

f = open('../path1/小娃娃.txt',mode='wb')
msg = '你好'.encode('utf-8')
f.write(msg)
f.flush()  # 刷新
f.close()

add to

As long as a or ab, a + end of the file is written to, regardless of the cursor at any position.

In append mode, the content of our written after the end of the file append

If the file does not exist a model will create a new file

f1 = open('../path1/小娃娃.txt',mode='a',encoding='utf-8')
msg = f1.write('这支烟灭了以后')

ab this mode, try their own does not have much difference

Guess you like

Origin www.cnblogs.com/luckinlee/p/11620030.html