我有一些 python 代码来解压缩文件然后删除它(原始文件),但我的代码捕获了一个异常:它无法删除文件,因为它正在使用中。
我认为问题是当删除代码运行时,解压 Action 还没有完成,所以抛出异常。那么,如何在删除文件前检查解压操作的运行状态呢?
file = zipfile.ZipFile(lfilename)
for filename in file.namelist():
file.extract(filename,dir)
remove(lfilename)
请您参考如下方法:
ZipFile 的文档说:
ZipFile is also a context manager and therefore supports the with statement.
因此,我建议您执行以下操作:
with zipfile.ZipFile(lfilename) as file:
file.extract(filename, dir)
remove(lfilename)
使用 with 语句的一个优点是文件会自动关闭。它也很漂亮(简短、简洁、有效)。
另见 PEP 343 .
