我正在使用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文件时,为什么我的列表会缩短?
如您所见,该文件未关闭,因为您省略了括号:应该是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一切顺利!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句