如何使用Python解压缩一个已关闭的zip文件

3

我正在尝试使用ZipFile模块提取一个已关闭的zip文件,但是:

"open()、read()和extract()方法可以接受文件名或ZipInfo对象。"

def ExtractZip(zipFile, path):
   zipfile.ZipFile.open(zipFile, 'r')
   zipFile.extractall(path)

这是我的代码,它返回了一个错误。(在运行此函数之前,我关闭了一个zip文件并且无法删除它)我该如何处理?谢谢。

哪个Python版本? - theonlygusti
2.7 Python 版本 - Shir K.
“closed” ZIP文件是什么意思? - user149341
4个回答

1
  1. 虽然您的方法没有问题,但这不是使用zipfile模块的最佳方式
  2. 您没有将zipfile对象存储在任何变量中,因此无法访问它

您的函数应该如何看起来

import zipfile

def extract_zip(path: str):
    with zipfile.Zipfile(path) as file:
        file.extractall()

这将把zip文件解压到与它相同的文件夹中。之所以更好,是因为它使用了一个上下文管理器,它会在你完成工作后自动关闭文件。

如果您想要将zip文件解压到另一个文件夹中

import zipfile
    
def extract_zip(path: str, extract_to: str):
    with zipfile.Zipfile(path) as file:
        file.extractall(path=extract_to)

这将把文件提取到您指定的文件夹中。此外,使用这种方法,您无需指定读取模式,因为默认情况下已经完成了。


0
显然,根据所有 ZipFile 示例,您需要将归档存储在变量中。
def ExtractZip(zipFile, path):
   archive = zipfile.ZipFile.open(zipFile, 'r')
   archive.extractall(path)

0
假设您的文件名为Archive.zip
那么,请执行以下操作:
import zipfile
f = zipfile.ZipFile('Archive.zip')
f.extractall()

就是这样。如果你想把内容放在其他地方,你也可以提供一个可选的path参数给extractall

更多信息可以在Python文档这里找到。


不回答OP的问题 - Joey Baruch

0

这是我如何使用zipfile来访问归档文件。

import zipfile
zippedArchive = zipfile.ZipFile('Scripts.zip')
print zippedArchive.open("Scripts/PlayPauseYouTube.scpt").read()

将打印PlayPauseYouTube.scpt文件的内容。

如果你想把压缩文件中的所有文件提取到另一个位置,你可以使用zipfile.extractall

ZipFile.extractall([path[, members[, pwd]]])  

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by zipfile.namelist(). pwd is the password used for encrypted files.

import zipfile
zippedArchive = zipfile.ZipFile('Scripts.zip')
zippedArchive.extractall()

不回答 OP 的问题 - Joey Baruch

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