user299709 user299709 - 9 months ago 39
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 Source

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.

import os

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



$ python 
$ cat log.txt