Skip to content Skip to sidebar Skip to footer

Newline "\n" Not Working When Writing A .txt File Python

for word in keys: out.write(word+' '+str(dictionary[word])+'\n') out=open('alice2.txt', 'r') out.read() For some reason, instead of getting a new line for every word i

Solution 1:

Suppose you do:

>>>withopen('/tmp/file', 'w') as f:...for i inrange(10):...      f.write("Line {}\n".format(i))...

And then you do:

>>>withopen('/tmp/file') as f:...   f.read()... 
'Line 0\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\n'

It appears that Python has just written the literal \n in the file. It hasn't. Go to the terminal:

$ cat /tmp/file
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9

The Python interpreter is showing you the invisible \n character. The file is fine (in this case anyway...) The terminal is showing the __repr__ of the string. You can print the string to see the special characters interpreted:

>>>s='Line 1\n\tLine 2\n\n\t\tLine3'>>>s
'Line 1\n\tLine 2\n\n\t\tLine3'
>>>print s
Line 1
    Line 2

        Line3

Note how I am opening and (automatically) closing a file with with:

withopen(file_name, 'w') as f:
  # do something with a write only file# file is closed at the end of the block

It appears in your example that you are mixing a file open for reading and writing at the same time. You will either confuse yourself or the OS if you do that. Either use open(fn, 'r+') or first write the file, close it, then re-open for reading. It is best to use a with block so the close is automatic.

Post a Comment for "Newline "\n" Not Working When Writing A .txt File Python"