【发布时间】:2020-12-22 20:22:51
【问题描述】:
我有一个类似这样的文件结构:
/a.zip
/not_a_zip/
内容
/b.zip
内容
我想创建一个目录 a 并将 a.zip 提取到其中以及所有嵌套的压缩文件所在的位置,因此我得到如下内容:
/a/
/not_a_zip/
内容
/b/
内容
我尝试了this 解决方案,但我遇到了错误,因为在我的主目录中我有子目录以及 zip 文件。
我希望能够将主 zip 文件提取到同名目录中,然后能够提取其中的所有嵌套文件,无论它们嵌套多深。
编辑:我当前的代码是这样的
archive = zipfile.ZipFile(zipped, 'r')
for file in archive.namelist():
archive.extract(file, resultDirectory)
for f in [filename for filename in archive.NameToInfo if filename.endswith(".zip")]:
# get file name and path to extract
fileToExtract = resultDirectory + '/' + f
# get directory to extract new file to
directoryToExtractTo = fileToExtract.rsplit('/', 1)
directoryToExtractTo = directoryToExtractTo[0] + '/'
# extract nested file
nestedArchive = zipfile.ZipFile(fileToExtract, 'r')
for file in nestedArchive.namelist():
nestedArchive.extract(fileToExtract, directoryToExtractTo)
但我收到此错误:
KeyError: "There is no item named 'nestedFileToExtract.zip' in the archive"
即使它存在于文件系统中
【问题讨论】: