我正在编写一个程序,将一些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
完全相同,但使用字符串。你知道吗您需要编辑remove部分,以便它优雅地处理不存在的案例。你知道吗
另见Most pythonic way to delete a file which may not exist
您可以在单独的函数中提取静默删除。你知道吗
同样,从另一个同样的问题:
我个人更喜欢后一种方法——它是明确的。你知道吗
相关问题 更多 >
编程相关推荐