简体   繁体   English

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

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

I have two python files, both of them in the same folder. 我有两个python文件,它们都在同一个文件夹中。 The main file executes the whole function, making my program what I want it to do. 主文件执行整个功能,使程序成为我想要的功能。 The other file writes data to a text file. 另一个文件将数据写入文本文件。 However, there's one issue with writing data to the text file: instead of writing each time new lines to the existing text, it completely overwrites the whole file. 但是,将数据写入文本文件存在一个问题:与其每次都在现有文本中添加新行,不如将新行完全写入整个文件。

File responsible for writing data(writefile.py) 负责写入数据的文件(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')

I've tried out couple of things such as .join(text) or running the code from writefile.py in the main file. 我已经尝试了一些方法,例如.join(text)或从主文件中的writefile.py运行代码。 Nothing seems to work.. 似乎没有任何效果。

The problem lies with the line 问题在于线

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

this one opens the file in write mode, to append you want 'a' option so just change to 这将以写入模式打开文件,以追加您想要的“ a”选项,因此只需更改为

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

and you should be fine 你应该没事的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM