当 python 脚本崩溃时,csv 编写器留下空输出文件

csv writer leaves empty output file when the python script crashes

我有一个脚本可以对文件进行一些分析,然后将结果写入 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 文件中获取数据。

我做错了什么?

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

强制写入文件
file.flush()

每当您想将您的作品保存到文件中时执行此操作。

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