我有一个关于python的非常基本的问题。我想拆分以下列表中的项目,并将其打印到文本文件中。
import pandas as pd
s = ['"9-6": 1', ' "15-4": 1', ' "12-3": 1', ' "8-4": 1', ' "8-5": 1', ' "8-1": 1']
print type(s)
for i in s:
j = i.split(',')
with open("out.txt","w") as text_file:
text_file.write("{}".format(j))
但是,我的代码只打印最后一个值。显然,它不会占用for循环块中的最后几行。谁能指出我哪里错了?谢谢!
发布于 2016-11-11 13:04:41
您没有追加这些值。你每次都在重写。试着这样做:
with open("out.txt","a+") as text_file:
在这里,我将"w“替换为"a+”。
完整代码:
import pandas as pd
s = ['"9-6": 1', ' "15-4": 1', ' "12-3": 1', ' "8-4": 1', ' "8-5": 1', ' "8-1": 1']
print type(s)
for i in s:
j = i.split(',')
with open("out.txt","a+") as text_file:
text_file.write("{}".format(j))
发布于 2016-11-11 13:08:22
每次你使用'w‘选项打开out.txt时,它甚至在你写任何东西之前就会完全擦除该文件。您应该将with语句放在for循环开始之前,以便文件只打开一次。
发布于 2016-11-11 13:12:54
for循环的每一次迭代,你截断你的文件内容。“清空文件”。这是因为当使用开放模式时,PythonPython会隐式截断文件,因为您已经在上一次迭代中创建了文件。Python 2.7中记录了这种行为:
..“w”用于编写to files..
请改用选项a+
,该选项会附加到文件中。Python 2.7文档也注意到了这一点:
..'a‘表示追加..
这意味着:
...open('out.txt' 'w')...
应该是:
...open('out.txt', 'a')...
https://stackoverflow.com/questions/40541350
复制相似问题