0

编写从 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
4

2 回答 2

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 循环的每次迭代中以写入模式打开文件。这意味着它的内容不断被覆盖。

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

于 2013-11-09T15:53:53.380 回答
3

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

将打开的文件移出循环:

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

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

以模式打开文件会w显式截断它(删除所有数据)。引用open()函数文档

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

如果您必须为每次迭代打开一个文件,至少打开文件以进行追加,使用'a'

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

for e in L:
    with open('outfile.txt', 'a') as outfile:
        print (e, file=outfile)
于 2013-11-09T15:54:09.750 回答