Search code examples
pythonnewlinefile-writing

Write a new line to a file (Python 3)


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


Solution

  • 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))