尝试在解压Python Zip文件后删除文件

4

关于这个问题已经有很多帖子了,我尝试了所有推荐的解决方案,但是它们似乎都不起作用。我想删除一个zip压缩包,但在解压后我无法删除它。

我尝试了使用os.removeos.unlink以及使用with语句等所有方法,但仍然无法删除。

WindowsError: [Error 32] The process cannot access the file because it is being used by another process:

Many thanks in advance

def Unzip(f, password, foldername):
    '''
    This function unzips a file, based on parameters, 
    it will create folders and will overwrite files with the same 
    name if needed.
    '''

    if foldername != '':
        outpath = os.path.dirname(f) + '\\'+ foldername
        if not os.path.exists(outpath):
            os.mkdir(outpath)
    else:
        outpath = os.path.dirname(f)
        if not os.path.exists(outpath):
            os.mkdir(outpath)

    if password == '':
        z = zipfile.ZipFile(f)
        z.extractall(outpath)
        z.close()
        os.unlink(f)

    else:
        z = zipfile.ZipFile(f)
        z.extractall(outpath, None, password)
        z.close()
        os.unlink(f)

更新,我调整了代码,现在它可以正常工作:

    z = zipfile.ZipFile(f)
    z.extractall(outpath)
    z.close()
    del z
    os.unlink(f)

你应该在你的代码中添加删除部分。 - wardk
你能否在Python之外“手动”删除文件? - CristiFati
Python使用布尔强制转换,因此您的代码可以通过执行if foldername:if not password来简化。此外,使用os.path.join而不是手动拼接字符串。 - deets
如果您(在希望通过将z.close()os.unlink放置在if password...后面来统一两个代码路径之后)在unlink之前放置了del z,会发生什么? - deets
我可以在Windows中删除文件,我会尝试使用del z。 - Ethan Waldie
是的,del z 这个东西可以起作用。 - Ethan Waldie
1个回答

1
这是由一个漏洞引起的(问题16183),现在已经在Python 2和3的最新版本中修复。但是,作为早期版本的解决方法,请传递一个文件对象而不是路径:
with open(f, 'rb') as fileobj:
    z = zipfile.ZipFile(fileobj)
    z.extractall(outpath)
    z.close()
os.remove(f)

如果我在调试器中运行,它可以工作,但当我运行脚本时仍然会出错。 - Ethan Waldie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接