换行符“\n”在编写.txt文件Python时不工作

2024-10-01 19:15:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

出于某些原因,python并没有为字典中的每个单词获取新行,而是在每个键和值之间打印\n。 我甚至试着分开写新行,像这样。。。在

^{pr2}$

我该怎么办?在


Tags: intxtforreaddictionary字典原因open
1条回答
网友
1楼 · 发布于 2024-10-01 19:15:09

假设你这样做:

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

然后你会:

^{pr2}$

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字符。文件很好(在本例中…)终端显示的是字符串的^{}。您可以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块,这样关闭是自动的。在

相关问题 更多 >

    热门问题