Newline “\n” not Working when Writing a .txt file Python

一世执手 提交于 2019-12-02 02:08:58

问题


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 in the dictionary, python is literally printing \n between every key and value. I have even tried to write new line separately, like this...

for word in keys:
    out.write(word+" "+str(dictionary[word]))
    out.write("\n")
    out=open("alice2.txt", "r")
    out.read()

What do I do?


回答1:


Suppose you do:

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

And then you do:

>>> with open('/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:

with open(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.



来源:https://stackoverflow.com/questions/44401883/newline-n-not-working-when-writing-a-txt-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!