【问题标题】:List being shortened when writing it to a txt file将其写入 txt 文件时列表被缩短
【发布时间】:2015-01-21 10:48:25
【问题描述】:

我正在使用 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 文件时会缩短?

【问题讨论】:

  • 我看不出代码有什么问题。它适用于我的 Python 3.4.1。你有什么理由不直接将它写入文件,而不是使用 print 函数的文件参数?
  • 这太奇怪了。我的不会在第一个代码中将所有内容都写入文件。我将如何直接写入文件?我对 python 还是很陌生,所以只知道做每件事的一种方法
  • 我无法回答“为什么它不起作用?”这个问题,因为它对我有用。但是我确实发布了一个可能对您有所帮助的答案。祝你好运。
  • 我发现问题是写了 f.close 而不是 f.close()
  • 当我重新输入您的示例时,我不假思索地添加了括号。所以它对我有用。应该完成复制/粘贴。但是请参阅我的答案以获得更好的方法。

标签: list file python-3.x


【解决方案1】:

正如您所发现的,该文件没有被关闭,因为您去掉了括号:应该是 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 好运!

【讨论】:

  • 我发现问题是写了 f.close 而不是 f.close() 我不知道为什么它会因此停止写入文件。感谢您使用正确的 python 写入文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2015-06-12
  • 2021-08-06
  • 2021-10-12
  • 2012-06-17
相关资源
最近更新 更多