Search code examples
pythontextlines

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


Solution

  • 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