将其写入txt文件时缩短列表

时间:2014-11-23 18:35:58

标签: list file python-3.x

我正在使用Python 3.

我做了一些编码来获得两个列表,timlist和acclist,并将它们压缩成一个元组。我现在想要在文本文件的列中编写元组的每个元素。

f = open("file.txt", "w")
for f1, f2 in zip(timlist, acclist):
print(f1, "\t", f2, "\n", file=f)    
f.close

当我运行它时,我只获得部分列表但是如果我将其作为

运行
f = open("file.txt", "w")
for f1, f2 in zip(timlist, acclist):
print(f1, "\t", f2, "\n")
f.close

我得到了我想要的全部东西。为什么在将其写入txt文件时缩短了我的列表?

1 个答案:

答案 0 :(得分:0)

正如您所发现的那样,文件未关闭,因为您将括号关闭:应该是f.close()而不是f.close。但我想我也会发布一个答案,说明如何在一个更惯用的Python中执行此操作,即使在循环中发生错误,也会为您完成对f.close()的调用:

timlist = [1,2,3,4]
acclist = [9,8,7,6]

with open('file.txt', 'w') as f: # use a context for the file, that way it gets close for you automatically when the context ends
    for f1, f2 in zip(timlist, acclist):
        f.write('{}\t{}\n'.format(f1, f2)) # use the format method of the string object to create your string and write it directly to the file

祝学习Python好运!