python - Python - 关闭文件和 IOError
问题描述
我正在编写一个将数据写入文件的程序,并且每小时都会生成一个新文件,并带有精确的标题。当存储空间已满时,它要么停止应用程序,要么删除文件夹中创建的最旧文件。
fp = open (fileNamePath, 'a')
fp.write('%s' % buffer)
try:
fp.close()
except IOError:
# delete file or close app
但是当涉及到except时,它只是跳过它,并显示IOError。
谢谢 !
解决方案
我在谷歌上寻找解决方案,有人建议使用:
try:
with open(filePath,'a') as fp:
fp.write('%s' % buffer)
except IOError as exc:
# Handling exception
好吧,我不明白为什么,但它是这样工作的。
谢谢大家!
推荐阅读
- lambda-calculus - 何时重命名 lambda 演算中的变量?
- python - 在python中使用VTK查找具有负平均曲率的.stl文件的单元格
- vue.js - 将数据附加到 FormData() 时为 null
- java - 使用我的 Python TCP 服务器与我的 Android 应用程序通信
- html - 尝试以百里香叶形式填充复选框时无法解析为表达式
- html - 在 html 标签中插入 React 变量作为属性
- javascript - 从 AWS lambda 有效负载解析 JSON
- php - 正则表达式在 PHP 中匹配时间
- go - 为什么 log.Printf() 不打印?
- php - 我想在表单中显示外键的值