首页 > 解决方案 > 如果发生异常,删除 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

发生异常时如何删除文件?

标签: python

解决方案


分离文件读取和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)

推荐阅读