Yan*_*nis 10 python zip unzip zipfile python-3.x
我有一个zip文件,其中包含三个zip文件,如下所示:
zipfile.zip\
dirA.zip\
a
dirB.zip\
b
dirC.zip\
c
Run Code Online (Sandbox Code Playgroud)
我想在具有这些名称(dirA,dirB,dirC)的目录中提取zip文件中的所有内部zip文件.
基本上,我想最终得到以下架构:
output\
dirA\
a
dirB\
b
dirC\
c
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
import os, re
from zipfile import ZipFile
os.makedirs(directory) # where directory is "\output"
with ZipFile(self.archive_name, "r") as archive:
for id, files in data.items():
if files:
print("Creating", id)
dirpath = os.path.join(directory, id)
os.mkdir(dirpath)
for file in files:
match = pattern.match(filename)
new = match.group(2)
new_filename = os.path.join(dirpath, new)
content = archive.open(file).read()
with open(new_filename, "wb") as outfile:
outfile.write(content)
Run Code Online (Sandbox Code Playgroud)
但它只提取zip文件,我最终得到:
output\
dirA\
dirA.zip
dirB\
dirB.zip
dirC\
dirC.zip
Run Code Online (Sandbox Code Playgroud)
任何建议,包括代码段将非常感激,因为我已经尝试了很多不同的东西,并阅读文档没有成功.
解压缩zip文件时,您需要将内部zip文件写入内存而不是磁盘上.要做到这一点,我已经习惯了BytesIO.
看看这段代码:
import os
import io
import zipfile
def extract(filename):
z = zipfile.ZipFile(filename)
for f in z.namelist():
# get directory name from file
dirname = os.path.splitext(f)[0]
# create new directory
os.mkdir(dirname)
# read inner zip file into bytes buffer
content = io.BytesIO(z.read(f))
zip_file = zipfile.ZipFile(content)
for i in zip_file.namelist():
zip_file.extract(i, dirname)
Run Code Online (Sandbox Code Playgroud)
如果运行extract("zipfile.zip")有zipfile.zip如下:
zipfile.zip/
dirA.zip/
a
dirB.zip/
b
dirC.zip/
c
Run Code Online (Sandbox Code Playgroud)
输出应该是:
dirA/
a
dirB/
b
dirC/
c
Run Code Online (Sandbox Code Playgroud)
对于提取嵌套 zip 文件(任何级别的嵌套)并清理原始 zip 文件的函数:
import zipfile, re, os
def extract_nested_zip(zippedFile, toFolder):
""" Extract a zip file including any nested zip files
Delete the zip file(s) after extraction
"""
with zipfile.ZipFile(zippedFile, 'r') as zfile:
zfile.extractall(path=toFolder)
os.remove(zippedFile)
for root, dirs, files in os.walk(toFolder):
for filename in files:
if re.search(r'\.zip$', filename):
fileSpec = os.path.join(root, filename)
extract_nested_zip(fileSpec, root)
Run Code Online (Sandbox Code Playgroud)
我尝试了其他一些解决方案,但无法让它们“就地”工作。我将发布我的解决方案来处理“就地”版本。注意:它会删除 zip 文件并用同名目录“替换”它们,因此如果您想保留,请备份您的 zip 文件。
策略很简单。解压目录(和子目录)中的所有 zip 文件,然后冲洗并重复,直到没有 zip 文件剩余。如果 zip 文件包含 zip 文件,则需要冲洗并重复。
import os
import io
import zipfile
import re
def unzip_directory(directory):
"""" This function unzips (and then deletes) all zip files in a directory """
for root, dirs, files in os.walk(directory):
for filename in files:
if re.search(r'\.zip$', filename):
to_path = os.path.join(root, filename.split('.zip')[0])
zipped_file = os.path.join(root, filename)
if not os.path.exists(to_path):
os.makedirs(to_path)
with zipfile.ZipFile(zipped_file, 'r') as zfile:
zfile.extractall(path=to_path)
# deletes zip file
os.remove(zipped_file)
def exists_zip(directory):
""" This function returns T/F whether any .zip file exists within the directory, recursively """
is_zip = False
for root, dirs, files in os.walk(directory):
for filename in files:
if re.search(r'\.zip$', filename):
is_zip = True
return is_zip
def unzip_directory_recursively(directory, max_iter=1000):
print("Does the directory path exist? ", os.path.exists(directory))
""" Calls unzip_directory until all contained zip files (and new ones from previous calls)
are unzipped
"""
iterate = 0
while exists_zip(directory) and iterate < max_iter:
unzip_directory(directory)
iterate += 1
pre = "Did not " if iterate < max_iter else "Did"
print(pre, "time out based on max_iter limit of", max_iter, ". Took iterations:", iterate)
Run Code Online (Sandbox Code Playgroud)
假设您的 zip 文件已备份,您可以通过调用 来完成这一切unzip_directory_recursively(your_directory)。