写入 .txt 文件时换行符“\n”不起作用 Python

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()

出于某种原因,python 不是为字典中的每个单词换行,而是字面上在每个键和值之间打印 \n。 我什至试过单独写新行,像这样...

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

我该怎么办?

假设你这样做:

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

然后你做:

>>> 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'

出现 Python 刚刚在文件中写入了文字 \n。它没有。转到终端:

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

Python 解释器正在向您展示不可见的 \n 字符。该文件很好(无论如何在这种情况下......)终端显示字符串的 __repr__ 。您可以 print 字符串来查看解释的特殊字符:

>>> 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

注意 如何 我打开和(自动)关闭一个文件 with:

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

在您的示例中,您正在混合打开一个文件以供同时读取和写入。如果你这样做,你要么混淆自己,要么混淆 OS。使用 open(fn, 'r+') 或先写入文件,关闭它,然后重新打开以供读取。最好使用 with 块,以便自动关闭。