【问题标题】:csv writer leaves empty output file when the python script crashes当 python 脚本崩溃时,csv writer 留下空的输出文件
【发布时间】:2020-07-13 21:39:40
【问题描述】:

我有一个脚本可以对文件进行一些分析,然后将结果写入 CSV 文件。在伪代码中:

while (there are still files to analyze): 
  do_analysis
  writer.writerow({... lots of columns names and the analysis results data... })

如果脚本完成,则数据确实在 csv 文件中。 但如果脚本崩溃 - 文件是空的。但是在每个文件分析完成后都会调用 writer.writerow() 行,因此我希望在 csv 文件中获取崩溃前分析的所有文件的数据。

我做错了什么?

【问题讨论】:

标签: python csv writer


【解决方案1】:

writerow 不会立即写入文件,大部分写入是在关闭文件时完成的。 您可以使用

强制写入文件
file.flush()

只要您想将作品保存到文件中,请执行此操作。

更多信息https://www.tutorialspoint.com/python/file_flush.htm

【讨论】:

  • 谢谢!这完成了这项工作。像我这样的新手注意: csv 文件的打开方式如下: with open(csvfilename, mode='w', newline='') as csv_file: 因此我使用: csv_file.flush()
猜你喜欢
  • 2015-06-02
  • 2018-08-21
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多