Я использую этот код:
with ZipFile(sourceZip, mode = "r") as extraction:
extraction.extractall(extractionPath)
extraction.close()
Что происходит, так это то, что он извлекает только первый слой Zip-файлов из sourceZip в ExtractPath.
Я прочитал «https://docs.python.org/3/library/zipfile.html#», и мне нужно получить код для извлечения всех zip-файлов второго уровня.
Модуль Python zipfile
по умолчанию извлекает только первый слой файлов из заархивированного архива. Чтобы извлечь вложенные ZIP-файлы, вы можете использовать рекурсию:
def extract_all(source_zip, extraction_path):
with zipfile.ZipFile(source_zip, mode = "r") as zip_ref:
for zip_info in zip_ref.infolist():
extracted_file_path = os.path.join(extraction_path, zip_info.filename)
if zip_info.is_dir():
os.makedirs(extracted_file_path, exist_ok=True)
elif zip_info.filename.endswith(".zip"):
with zip_ref.open(zip_info.filename) as nested_zip:
extract_all(nested_zip, extracted_file_path)
else:
zip_ref.extract(zip_info, extraction_path)
Рекурсивно извлекайте содержимое архивного файла, пока не будут извлечены все вложенные уровни. Переберите содержимое каждого zip-файла, определяя, является ли файл zip-архивом, а затем извлекая содержимое.
import os
import zipfile
def extract_zipfile_recursive(zip_file_path, extract_to):
"""
Recursively extract the contents of a zip file and any nested zip files.
zip_file_path: Path to the zip file.
extract_to: Directory where extracted files should be saved.
"""
with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
# Extract all contents of the zip file to the extract_to directory
zip_ref.extractall(extract_to)
# Iterate through each extracted item (files and directories)
for item in zip_ref.infolist():
# Check if the item is a directory or a file
if item.is_dir():
# Recursively extract contents of nested zip files in this directory
dir_path = os.path.join(extract_to, item.filename)
extract_zipfile_recursive(os.path.join(extract_to, item.filename), dir_path)
elif item.filename.lower().endswith(".zip"):
# The item is a zip file, recursively extract its contents
nested_zip_path = os.path.join(extract_to, item.filename)
nested_extract_to = os.path.join(extract_to, os.path.splitext(item.filename)[0])
extract_zipfile_recursive(nested_zip_path, nested_extract_to)
# Example usage:
zip_file_path = "path/to/your/nested.zip"
extract_to_directory = "path/to/extracted/files"
# Create the directory if it doesn't exist
os.makedirs(extract_to_directory, exist_ok=True)
# Extract contents of the nested zip file recursively
extract_zipfile_recursive(zip_file_path, extract_to_directory)
Код выполняет свою работу, верно? Этот «второй слой» zip-файлов, о котором вы говорите, представляет собой новый набор файлов, которые только что были созданы. Если вы хотите разархивировать их, вам придется снова запустить этот код для каждого из этих файлов.