gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:41:48 25 4
gpt4 key购买 nike

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__的字符串。您可以打印 字符串以查看解释的特殊字符:

>>> 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 block ,这样关闭是自动的。

关于python - 换行符 "\n"在编写 .txt 文件 Python 时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44401883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com