【问题标题】:Why is my Python script not writing the last few lines into my file?为什么我的 Python 脚本没有将最后几行写入我的文件?
【发布时间】:2013-04-03 02:45:12
【问题描述】:

我一直在尝试从一个文件中读取数字列表,将它们拆分,然后放入另一个文件中。在弄乱了一些调试打印之后,我得出的结论是,问题不在于我的字符串的循环或拆分,而在于我实际编写的脚本的最后一行> 到新文件。

而不是像我想要的那样写,它通过文件的大部分方式,然后不写文件的最后几行。我可以在脚本中写的东西的数量是否有限制?还是这里发生了其他事情?

这是脚本: 导入字符串

#constants to name out in/out files
INFILE = 'newkicBright.txt'
OUTFILE = 'out.txt'

#open both files
inHandle = open(INFILE, 'r')
outHandle = open(OUTFILE, 'w')

#console verifies that everything's opened
print inHandle
print outHandle

#read our data into the file!
for line in inHandle:
    nums = string.split(line)
    for num in nums:
        num += " PLACEHOLDER\n"
        outHandle.write(num)

【问题讨论】:

  • Python 对您可以写入文件的数量没有任何限制。你能举出一小部分数据来证明这个问题吗?
  • 您似乎没有关闭文件(这是使用with open(filename) as handle: 模式的好主意的原因之一。可能只是尚未刷新缓冲区。跨度>

标签: python file limit


【解决方案1】:

您需要关闭文件处理程序,以便它真正写入并清理所有内容。

outHandle.close()

将其添加到末尾。

close 暗示 flush: does close() imply flush() in Python?

【讨论】:

  • 啊!我有一种感觉,就是这样。现在完美运行。谢谢!
猜你喜欢
  • 2015-06-08
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多