繁体   English   中英

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

[英]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

在您的示例中,您正在混合打开的文件以便同时进行读写。 如果你这样做,你会混淆自己或操作系统。 使用open(fn, 'r+')或首先写入文件,关闭它,然后重新打开以进行读取。 最好使用with块,以便自动关闭。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM