【问题标题】:Python how to keep writing to a file without erasing what's already therePython如何继续写入文件而不删除已经存在的内容
【发布时间】:2014-10-22 13:34:26
【问题描述】:

在 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)

【问题讨论】:

  • 因为它是 python 3.3,你应该使用 open('file.txt', 'w') 作为文件而不是直接打开
  • @user3012759 该功能是在 Python 2.5 中引入的

标签: python python-3.x file-io windows-7 python-3.3


【解决方案1】:

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

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

【讨论】:

  • 但我没有重新打开文件。我又给它写信了!
  • @LukeDinkler:然后向我们展示您的代码;如果行被替换,那么你正在做一些不寻常的事情。
  • @LukeDinkler:您正在重新打开文件。每次拨打open()
  • 哦!愚蠢的错误!现在如何将每一行写在新行上?
  • @LukeDinkler:在您编写的文本中添加换行符。
【解决方案2】:

为了解决此类问题并在包括实时应用程序在内的所有应用程序上工作,您必须首先在循环外以附加模式打开文件 并在循环内以写入模式打开同一个文件。

这是不同上下文中的示例(实时删除重复项)。

import sched, time
s = sched.scheduler(time.time, time.sleep)
outfile = open('D:/RemoveDup.txt', "a")
def do_something(sc):  #loop  
    outfile = open('D:/RemoveDup.txt', "w")
    #do your stuff........    
    infile = open('D:/test.txt', "r")
    lines_seen = set()
    for line in infile:
        if line not in lines_seen:
            outfile.write(line)
            lines_seen.add(line)
    s.enter(10, 1, do_something, (sc,))
    s.enter(10, 1, do_something, (s,))
s.run()

【讨论】:

    猜你喜欢
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多