如何在python中同时在一个变量中以读取和追加模式打开文件

Bal*_*iya 11 python file

'r'将读取一个文件,'w'从一开始就在文件中写入文本,然后'a'追加。如何打开文件以同时读取和追加?

我尝试了这些,但出现错误:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")
Run Code Online (Sandbox Code Playgroud)

错误:

invalid mode: 'r,a'
Run Code Online (Sandbox Code Playgroud)

Tre*_*edJ 15

您正在寻找r+ora+模式,它允许对文件进行读写操作(查看更多)。

使用r+,位置最初位于开头,但阅读一次会将其推向结尾,允许您追加。使用a+,位置最初位于末尾。

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")
Run Code Online (Sandbox Code Playgroud)
with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")
Run Code Online (Sandbox Code Playgroud)

如果您需要进行完整的重读,您可以通过执行 返回到起始位置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")
Run Code Online (Sandbox Code Playgroud)