我有以下Python脚本。我注意到open()每次在a read()或a 之后都必须要归档write()。那是因为文件在执行此类操作后会自动关闭吗?
text_file = open('Text.txt','r')
print 'The file content BEFORE writing content:'
print text_file.read()
text_file = open('Text.txt','a')
text_file.write(' add this text to the file')
print 'The file content AFTER writing content:'
text_file = open('Text.txt','r')
print text_file.read()
Run Code Online (Sandbox Code Playgroud)
谢谢。
在r+模式下打开seek(0):
with open('Text.txt', 'r+') as text_file:
print 'The file content BEFORE writing content:'
print text_file.read()
text_file.write(' add this text to the file')
print 'The file content AFTER writing content:'
text_file.seek(0)
print text_file.read()
Run Code Online (Sandbox Code Playgroud)
印刷品:
The file content BEFORE writing content:
abc
The file content AFTER writing content:
abc add this text to the file
Run Code Online (Sandbox Code Playgroud)
该文档具有详细信息:
“ +”打开磁盘文件以进行更新(读取和写入)
seek()使您可以在文件中四处移动:
更改流的位置。
将流位置更改为给定的字节偏移量。偏移是相对于wherece指示的位置进行解释的。其中的值是:
- 0-流的开始(默认); 偏移量应为零或正
- 1-当前流位置; 偏移量可能为负
- 2-流结束; 偏移量通常为负
返回新的绝对位置。