Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“新线”\";在Python中编写.txt文件时不工作_Python_Dictionary_Text Files_File Writing - Fatal编程技术网

“新线”\";在Python中编写.txt文件时不工作

“新线”\";在Python中编写.txt文件时不工作,python,dictionary,text-files,file-writing,Python,Dictionary,Text Files,File Writing,出于某种原因,python并没有为字典中的每个单词换行,而是在每个键和值之间打印。 我甚至试着分别写新行,像这样 for word in keys: out.write(word+" "+str(dictionary[word])+"\n") out=open("alice2.txt", "r") out.read() 我该怎么办?假设您: for word in keys: out.write(word+" "+str(dictionary[word]))

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

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

假设您:

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))
... 
Python似乎刚刚在文件中写入了文本
\n
。没有。前往终点站:

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

注意我是如何用
打开和(自动)关闭文件的:

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

在您的示例中,似乎您正在混合一个同时打开以进行读写的文件。如果你这样做,你要么会混淆你自己,要么会混淆操作系统。使用
open(fn,'r+')
或先写入文件,关闭它,然后重新打开以进行读取。最好与
块一起使用
,以便自动关闭

您确定您的文字中没有
\n
作为旁注,为什么不在打开另一个文件之前关闭文件?这里有很多错误。您正在编写然后打开?您是在python shell中还是在txt文件(使用标准文本编辑器)中可视化结果,我很确定结果将与您在后者中预期的一样…为什么要打开您的文件,当您在
r
模式下打开它时,在
键中找到下一个
word
时,您希望如何写入它?
with open(file_name, 'w') as f:
  # do something with a write only file
# file is closed at the end of the block