简体   繁体   English

在python中解压缩后如何删除原始文件

[英]How to remove original file after unzipping it in python

I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. 我有一些python代码来解压缩文件,然后将其删除(原始文件),但是我的代码捕获了一个异常:它无法删除文件,因为它正在使用中。

I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. 我认为问题在于,运行删除代码时,解压缩操作尚未完成,因此引发了异常。 So, how can I check the run state of the unzip action before removing the file? 那么,如何在删除文件之前检查解压缩操作的运行状态?

file = zipfile.ZipFile(lfilename)
for filename in file.namelist():
    file.extract(filename,dir)
remove(lfilename)

The documentation for ZipFile says: ZipFile的文档说:

ZipFile is also a context manager and therefore supports the with statement. ZipFile还是上下文管理器,因此支持with语句。

So, I'd recommend doing the following: 因此,我建议您执行以下操作:

with zipfile.ZipFile(lfilename) as file:
    file.extract(filename, dir)
remove(lfilename)

One advantage of using a with statement is that the file is closed automatically. 使用with语句的一个优点是文件自动关闭。 It is also beautiful (short, concise, effective). 它也很漂亮(简短,简洁,有效)。

See also PEP 343 . 另请参阅PEP 343

Try closing the file before removing it. 尝试在关闭文件之前将其关闭。

file = zipfile.ZipFile(lfilename)
for filename in file.namelist():
    file.extract(filename,dir)

file.close()

remove(lfilename)

You must first close the file. 您必须首先关闭文件。

    file.close()
    remove(lfilename)

Alternatively you could do the following: 或者,您可以执行以下操作:

with ZipFile('lfilename') as file:
    for filename in file.namelist():
        file.extract(filename,dir)
remove(lfilename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM