Python 如何在文件中持续写入而不覆盖已有内容

3 投票
2 回答
10532 浏览
提问于 2025-04-18 18:51

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

2 个回答

0

为了处理这种问题,并且让所有应用程序都能正常工作,包括实时应用程序,你首先需要在循环外以追加模式打开一个文件,然后在循环内部以写入模式打开同一个文件。

下面是一个在不同场景下的例子(实时去重)。

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()
8

每次你打开一个文件进行写入时,文件里的内容会被清空(也就是被截断)。所以你可以选择以追加的方式打开文件,或者只打开一次文件并保持它一直打开。

要以追加的方式打开文件,可以在模式中使用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)

撰写回答