Ignesus
Ignesus

Reputation: 33

Python does not write newline to file, while it is supposed to

xadd = open('x.txt', 'w', encoding="utf-8")
hha = [ 'j', 'a', 's', 'o', 'n', '\\n', 'b', 'r', 'o', 'w', 'n']
a = ''.join(hha)
xadd.write(a)
xadd.close()

File's output is jason\nbrown. I can assume that the problem is with a variable because when I do it normally, without join file has newlines. Can someone explain me why is that not working and give me the solution for this problem?

Upvotes: 0

Views: 43

Answers (1)

scotty3785
scotty3785

Reputation: 7006

Simple fix. Your \\n should be \n

xadd = open('x.txt', 'w', encoding="utf-8")
hha = [ 'j', 'a', 's', 'o', 'n', '\n', 'b', 'r', 'o', 'w', 'n']
a = ''.join(hha)
xadd.write(a)
xadd.close()

Also consider using a context manager when you open files. This will automatically close the file even if an exception occurs and your code doesn't make it to the .close() line.

with open('x.txt', 'w', encoding="utf-8") as xadd:
    hha = [ 'j', 'a', 's', 'o', 'n', '\n', 'b', 'r', 'o', 'w', 'n']
    a = ''.join(hha)
    xadd.write(a)  

Upvotes: 2

Related Questions