2024-10-01 19:15:09 发布
网友
for word in keys: out.write(word+" "+str(dictionary[word])+"\n") out=open("alice2.txt", "r") out.read()
出于某些原因,python并没有为字典中的每个单词获取新行,而是在每个键和值之间打印\n。 我甚至试着分开写新行,像这样。。。在
我该怎么办?在
假设你这样做:
>>> with open('/tmp/file', 'w') as f: ... for i in range(10): ... f.write("Line {}\n".format(i)) ...
然后你会:
Python刚刚在文件中写入了\n,这似乎是。还没有。去终点站:
\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查看解释的特殊字符:
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
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块,这样关闭是自动的。在
open(fn, 'r+')
假设你这样做:
然后你会:
^{pr2}$Python刚刚在文件中写入了
\n
,这似乎是。还没有。去终点站:Python解释器向您显示不可见的} 。您可以
\n
字符。文件很好(在本例中…)终端显示的是字符串的^{print
查看解释的特殊字符:注意我如何使用
with
打开和(自动)关闭文件:在您的示例中,您混合了一个同时打开以进行读写的文件。如果你这样做,你会混淆你自己或者操作系统。使用
open(fn, 'r+')
或首先写入文件,关闭它,然后重新打开以进行读取。最好使用with
块,这样关闭是自动的。在相关问题 更多 >
编程相关推荐