编写.txt文件 Python 时换行符"n"不起作用


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 0nLine 1nLine 2nLine 3nLine 4nLine 5nLine 6nLine 7nLine 8nLine 9n'

IT 出现 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 1ntLine 2nnttLine3'
>>> s
'Line 1ntLine 2nnttLine3'
>>> print s
Line 1
    Line 2
        Line3

Note 我如何打开并(自动(用with关闭文件:

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

在您的示例中,您正在同时混合一个用于阅读和写作的文件。如果这样做,您将混淆自己或操作系统。使用open(fn, 'r+')或首先编写文件,将其关闭,然后重新打开以读取。最好使用with块,以使近距离自动。

最新更新