python - 如果发生异常,删除 JSON 文件
问题描述
我正在编写一个程序,它将一些 JSON 编码的数据存储在一个文件中,但有时生成的文件是空白的(因为没有找到任何新数据)。当程序找到数据并存储它时,我这样做:
with open('data.tmp') as f:
data = json.load(f)
os.remove('data.tmp')
当然,如果文件为空白,这将引发异常,我可以捕获但不允许我删除文件。我努力了:
try:
with open('data.tmp') as f:
data = json.load(f)
except:
os.remove('data.tmp')
我得到这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "MyScript.py", line 50, in run
os.remove('data.tmp')
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
发生异常时如何删除文件?
解决方案
分离文件读取和json加载怎么样? 行为与但使用字符串json.loads
完全相同。json.load
with open('data.tmp') as f:
dataread = f.read()
os.remove('data.tmp')
#handle exceptions as needed here...
data = json.loads(dataread)
推荐阅读
- python - Python/PIP 问题
- awk - 如何在执行 awk 时不删除标题
- javascript - 从 vue.js 检索数据属性到 jquery
- php - 如何获得父子层次结构的最大级别
- excel - 查找子字符串出现的最小列号(在多行范围内)
- nix - `?` 在 nix 语言中的集合之后是什么意思?
- ios - 删除实体后的核心数据版本控制/迁移
- java - 没有上下文路径的 Spring Boot 注册 API 调用
- c# - 如何将自定义对象列表绑定到 WPF 中的 DataGridComboboxColumn?
- eigen - 分解大量小矩阵时,Eigen partial_lu_inplace 中的瓶颈