2014-11-23 32 views
2

我使用Python 3它列出写作时到一个txt文件

我已经做了一些编码来获得两个列表,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文件时被缩短了?

+0

我没有看到任何代码错误。它适用于Python 3.4.1。你不是直接将它写入文件,而是使用打印函数的文件参数? – alan 2014-11-23 18:49:07

+0

太奇怪了。我不会在第一个代码中写入所有文件。如何直接写入文件?我对python仍然很陌生,所以只有真正知道做每件事的一种方法 – HannahR 2014-11-23 19:26:54

+0

我无法回答'为什么它不起作用?',因为它适用于我。但我确实发布了一个可以帮助你的答案。祝你好运。 – alan 2014-11-23 19:37:55

回答

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!

+0

我发现问题是写了f.close而不是f.close() 我不知道为什么它会停止写这个文件。 谢谢你正确的python写入文件 – HannahR 2014-11-23 20:04:08