写入从for循环中检索的数据

时间:2013-11-09 15:51:44

标签: python

从for循环中检索数据的最佳方法是什么?

L = ['abc','def','ghi']

for e in L:
    with open ('outfile.txt','w') as outfile:
        print (e, file=outfile)


##But the outfile.txt contains only:
##ghi
##
##        
##I have to write all the elements:
##abc
##def
##ghi

2 个答案:

答案 0 :(得分:4)

这是:

L = ['abc', 'def', 'ghi']    
with open('outfile.txt', 'w') as outfile:
    for e in L:
        # You could also do `outfile.write(e)`
        print(e, file=outfile)

最后,文件将如下所示:

abc
def
ghi

您当前的方法是以for循环的每次迭代以写入模式打开文件。这意味着它的内容不断被覆盖。

请记住,每次在写入模式下打开文件时,都会清除其所有内容。

答案 1 :(得分:3)

重新打开文件以编写每个循环迭代,每次清除文件。

移动循环的文件 out

L = ['abc','def','ghi']

with open('outfile.txt', 'w') as outfile:
    for e in L:
        print (e, file=outfile)

w模式打开文件会明确截断它(删除所有数据)。引用open() function documentation

  

其他常见值为'w'用于写入(如果文件已存在则截断文件)[...]

如果您 为每次迭代打开一个文件,至少使用'a'打开要追加的文件:

L = ['abc','def','ghi']

for e in L:
    with open('outfile.txt', 'a') as outfile:
        print (e, file=outfile)