【问题标题】:Saving a file without closing it in Python保存文件而不在 Python 中关闭它
【发布时间】:2018-11-05 15:14:55
【问题描述】:

假设我有一个我正在迭代的文件字典。我正在对每个文件进行一些处理,然后将其写入报告(注意:不使用csv mod)。

file_list = ['f1', 'f2', 'f3', 'f4']
report  = "C:/reports/report_%s"%(timestamp)
r = open(report, "w')

如果 f3 中发生的事情在脚本完成之前使脚本崩溃,会发生什么情况。我可以使用try-catch 来处理错误,但我不想只关闭报告。也许我希望脚本继续。脚本运行时可能出现电源故障。也许有多个try-catch 语句,我不想​​为每个错误关闭。本质上,我只想保存文件而不在列表的每次迭代中关闭它,这样如果发生崩溃,我仍然可以检索到该点之前写入报告的数据。我怎样才能做到这一点?我不能简单地做report.save(),对吧?我考虑过将flush()os.fsync() 一起使用,正如另一个question 中所解释的那样,但我不能100% 确定这适用于我的场景。关于如何在这里实现我的目标有什么建议吗?

try:
    ....do stuff...
    report.write(<stuff_output> + "\n")
    try:
        ....do more stuff....
        report.write(<stuff_output> + "\n")
    except:
        continue
    report.close()
except Exception as e:
    pass

【问题讨论】:

    标签: python-2.7 file file-writing saving-data


    【解决方案1】:

    看来我可以通过在正确的范围内使用flush()os.fsync() 并将r.close() 放在try 之外来解决这个问题。因此,即使它尝试并失败,它也会通过或继续并在最后关闭:

    try:
        for item in file_list:
            try:
                r.write("This is item: " + item + "\n")
    
            except:
                r.flush()
                os.fsync(r)
                continue
    
    except Exception as e:
        pass
    
    r.close()
    

    这将始终将"This is item: f1", "This is item: f2", "This is item: f3" 打印到报告中。

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2012-05-30
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多