user299709 user299709 - 14 days ago 5
Python Question

python: why doesn't this write to file on new line?

def log():
with open("log.txt", 'a') as f:
print ".log.txt"
f.write(msg.encode('utf-8') +"\n")


I call log() several times but doesn't write each msg on new line, and I have no clue why. I tried adding f.close() at the end but that didn't work either. Super frustrating!

Answer

I assume you wanted to define log() as log(msg) :). I tried it and it worked on my system (OS X). \n should work, but it's not 100% cross platform so try using os.linesep instead.

# test.py
import os

def log(msg):
    with open("log.txt", 'a') as f:
        f.write(msg.encode('utf-8') + os.linesep)

log('aaa')
log('bbb')

Then:

$ python test.py 
$ cat log.txt 
aaa
bbb