换行符" \ n"编写.txt文件时不工作

时间:2017-06-07 00:58:43

标签: python dictionary text-files file-writing

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

我该怎么办?

1 个答案:

答案 0 :(得分:5)

假设你这样做:

std::vector

然后你这样做:

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

出现,Python刚刚在文件中写了文字>>> 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' 。它没有。转到终端:

\n

Python解释器向您显示不可见的$ cat /tmp/file Line 0 Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 字符。文件很好(无论如何......)终端显示字符串的__repr__。您可以\n字符串查看解释的特殊字符:

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+')块,以便自动关闭。