我正在编写一个程序,该程序在文件中存储一些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
发生异常时如何删除文件?
答案 0 :(得分:1)
如何将文件读取和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)
答案 1 :(得分:0)
您需要编辑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
您可以在一个单独的函数中提取静默删除。
同样,来自另一个SO问题:
# 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)
我个人更喜欢后一种方法-这很明显。