0

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

Community
  • 1
  • 1
Dean
  • 301
  • 1
  • 3
  • 13
  • Forgot to add: the start function is executed more than once, thus the start function should write new lines each time with new content. – Dean Jan 08 '15 at 16:36
  • 3
    You have to use `'a'` mode when you open the file to append to it. You are using `'w'`. Also, what is that first `codecs.open` supposed to do? – tobias_k Jan 08 '15 at 16:39
  • @tobias_k sets the file encoding to utf-8 – Dean Jan 08 '15 at 16:51

1 Answers1

0

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

Johan
  • 1,633
  • 15
  • 22
  • Also, it probably should be `with codecs.open(..., 'a', 'utf-8') as ...`, otherwise that other lines does not make much sense. – tobias_k Jan 08 '15 at 16:46
  • I have no idea what the codec.open line does or what sense it makes, but the `with open`line will overwrite the file as it stands with the w option. – Johan Jan 08 '15 at 16:51
  • Thank you! It worked! But why? I thought 'a' does create a new file as 'a' stands for 'add' and later to open the file for writing it should be 'w'? – Dean Jan 08 '15 at 16:53
  • Here is where I end up constantly when I forget about the exact write modes. ;-) http://stackoverflow.com/a/1466036/870769. (also see the links to the BSD and Python 3 docs there). – sthzg Jan 08 '15 at 16:57
  • @sthzg: Thank you :) That's some nice info, will add that link to my favs! – Dean Jan 08 '15 at 17:02