换行符"\ n"编写.txt文件Python时无法正常工作 [英] Newline "\n" not Working when Writing a .txt file Python

查看:407
本文介绍了换行符"\ n"编写.txt文件Python时无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

由于某种原因,python并未在字典中的每个单词都换行,而是从字面上在每个键和值之间打印\ n. 我什至试图像这样单独写换行...

For some reason, instead of getting a new line for every word in the dictionary, python is literally printing \n between every key and value. I have even tried to write new line separately, like this...

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.还没有.转到终端:

It appears that Python has just written the literal \n in the file. It hasn't. Go to the terminal:

$ 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字符.该文件很好(无论如何,在这种情况下...)终端显示

The Python interpreter is showing you the invisible \n character. The file is fine (in this case anyway...) The terminal is showing the __repr__ of the string. You can print the string to see the special characters interpreted:

>>> 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打开和(自动)关闭文件:


Note how I am opening and (automatically) closing a file with 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块,以便自动关闭.

It appears in your example that you are mixing a file open for reading and writing at the same time. You will either confuse yourself or the OS if you do that. Either use open(fn, 'r+') or first write the file, close it, then re-open for reading. It is best to use a with block so the close is automatic.

这篇关于换行符"\ n"编写.txt文件Python时无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆