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

标签 python python-3.x file-io windows-7 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)

最佳答案

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

要打开文件进行追加,请使用 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)

或者在循环外打开文件:

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)

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

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)

关于Python如何在不删除已有内容的情况下继续写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25553031/

相关文章:

python - 如何在 ctypes 中取消引用 void*?

python - 如何使用环境变量覆盖Python配置

python - 如何在Python中获取数组中所有NaN元素的索引?

c - 为什么以下不将数组内容写入文件

python - 从 Python 生成和运行 Haskell 代码

Python 请求获取的参数是 ISO 日期时间不起作用

python - 在 python ffmpeg 上剪切、连接和转换

python - Python3 中的 mimetools.choose_boundary 函数在哪里?

windows - 名称中带有冒号的文件会发生什么情况?

C:使用 fread()/fgets() 而不是 fgetc() 逐行读取文本文件(具有可变长度行)( block I/O 与字符 I/O)