如果发生异常,请删除JSON文件

2024-04-25 13:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,将一些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

发生异常时如何删除文件?你知道吗


Tags: 文件数据in程序jsondataosas
2条回答

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

您需要编辑remove部分,以便它优雅地处理不存在的案例。你知道吗

import os
try:
    fn = 'data.tmp'
    with open(fn) as f:
        data = json.load(f)
except:
    try:
        if os.stat(fn).st_size > 0:
            os.remove(fn) if os.path.exists(fn) else None
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT:
            raise

另见Most pythonic way to delete a file which may not exist

您可以在单独的函数中提取静默删除。你知道吗

同样,从另一个同样的问题:

# python3.4 and above
import contextlib, os

try:
    fn = 'data.tmp'
    with open(fn) as f:
        data = json.load(f)
except:
    with contextlib.suppress(FileNotFoundError):
        if os.stat(fn).st_size > 0:
            os.remove(fn)

我个人更喜欢后一种方法——它是明确的。你知道吗

相关问题 更多 >