Python 不会每次都将新行写入文本文件

Python won't write each time new lines into text file

我有两个 python 文件,它们都在同一个文件夹中。主文件执行整个功能,使我的程序按照我的意愿执行。另一个文件将数据写入文本文件。 但是,将数据写入文本文件存在一个问题:不是每次都向现有文本写入新行,而是完全覆盖整个文件。

负责写入数据的文件(writefile.py)

import codecs
def start(text):
        codecs.open('D:\Program Files (x86)\Python342\passguess.txt', 'a', 'utf-8')
        with open('D:\Program Files (x86)\Python342\passguess.txt', 'w') as file:
                file.write(text + '\n')

我已经尝试了一些东西,例如 .join(text) 或从主文件中的 writefile.py 运行代码。似乎没有任何效果..

问题出在行

with open('D:\Program Files (x86)\Python342\passguess.txt', 'w') as file:

这个以写入模式打开文件,要附加你想要的 'a' 选项,所以只需更改为

with open('D:\Program Files (x86)\Python342\passguess.txt', 'a') as file:

你应该没事