如何在一个变量中同时在python中以读取和追加模式打开文件 [英] how to open file in read and append mode in python at the same time in one variable
问题描述
'r'
将读取文件,'w'
将从头开始在文件中写入文本,而'a'
将追加.如何打开文件以同时阅读和追加?
'r'
will read a file, 'w'
will write text in the file from the start, and 'a'
will append. How can I open the file to read and append at the same time?
我尝试了这些,但是出现了错误:
I tried these, but got errors:
open("filename", "r,a")
open("filename", "w")
open("filename", "r")
open("filename", "a")
错误:
invalid mode: 'r,a'
推荐答案
You're looking for the r+
or a+
mode, which allows read and write operations to files (see more).
使用r+
时,该位置最初位于开头,但是读取一次会将其推向末尾,从而允许您追加.使用a+
,该位置最初位于末尾.
With r+
, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+
, the position is initially at the end.
with open("filename", "r+") as f:
# here, position is initially at the beginning
text = f.read()
# after reading, the position is pushed toward the end
f.write("stuff to append")
with open("filename", "a+") as f:
# here, position is already at the end
f.write("stuff to append")
如果需要重新读取整个内容,则可以通过执行f.seek(0)
返回到起始位置.
If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0)
.
with open("filename", "r+") as f:
text = f.read()
f.write("stuff to append")
f.seek(0) # return to the top of the file
text = f.read()
assert text.endswith("stuff to append")
这篇关于如何在一个变量中同时在python中以读取和追加模式打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!