首页 > 解决方案 > Python - 关闭文件和 IOError

问题描述

我正在编写一个将数据写入文件的程序,并且每小时都会生成一个新文件,并带有精确的标题。当存储空间已满时,它要么停止应用程序,要么删除文件夹中创建的最旧文件。

fp = open (fileNamePath, 'a')
fp.write('%s' % buffer)
try:
    fp.close()
except IOError:
    # delete file or close app

但是当涉及到except时,它只是跳过它,并显示IOError。

谢谢 !

标签: pythonioerror

解决方案


我在谷歌上寻找解决方案,有人建议使用:

try:
    with open(filePath,'a') as fp:
        fp.write('%s' % buffer)

except IOError as exc:
    # Handling exception

好吧,我不明白为什么,但它是这样工作的。

谢谢大家!


推荐阅读