1

So, after reading many instances of this same question being answered, I'm still stuck. Why is this function not writing on a new line every time?:

def addp(wrd,pos):
    with open('/path/to/my/text/file', 'w') as text_file:
        text_file.write('{0} {1}\n'.format(wrd,pos))

It would seem as though the \n should be doing the trick. Am I missing something?

I'm running Ubuntu 15.04

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Gavyn Rogers
  • 37
  • 1
  • 8
  • You are using the wrong mode. You need to use [`'a'` (append)](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python), not `'w'` (write). – Rick Jun 21 '15 at 04:29

1 Answers1

3

It should be writing newline to the file all the time, the issue maybe that you are openning the file in w mode, which causes the file to be overwritten , hence for each call to the above function it completely overwrites the file with just the wrd,pos you send in , so the file only contains a single line.

You should try using a mode, which is for appending to the file.

def addp(wrd,pos):
    with open('/path/to/my/text/file', 'a') as text_file:
        text_file.write('{0} {1}\n'.format(wrd,pos))
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176