Python如何在不删除文件的情况下继续写入文件

Luk*_*ler 2 python file-io windows-7 python-3.x python-3.3

在 Windows 中编写我的 python 3.3 程序时,我遇到了一个小问题。我正在尝试将一些指令行写入文件以供程序执行。但是每次我 file.write() 下一行时,它都会替换上一行。我希望能够继续向该文件写入尽可能多的行。注意:使用 "\n" 似乎不起作用,因为您不知道将有多少行。请帮忙!这是我的代码(作为一个循环,我确实多次运行):

menu = 0
while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    file = open("file.txt", "w")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

每次打开文件进行写入时,它都会被擦除(截断)。打开文件进行追加,或者只打开一次文件并保持打开状态。

要打开文件进行追加,请使用a代替w模式:

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    file = open("file.txt", "a")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)
Run Code Online (Sandbox Code Playgroud)

在循环外打开文件:

file = open("file.txt", "w")

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)
Run Code Online (Sandbox Code Playgroud)

或仅在您第一次需要时使用一次:

file = None

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if file is None:
        file = open("file.txt", "w")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)
Run Code Online (Sandbox Code Playgroud)