简体   繁体   中英

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

I have two python files, both of them in the same folder. 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)

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. 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

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

and you should be fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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