Извлечь изображения из архива
Достаёт из zip или tar только картинки заданных форматов и сохраняет структуру папок.
Что делает скрипт
Скрипт фильтрует элементы по расширению и минимальному размеру, проверяет путь и не трогает остальные файлы. По умолчанию сохраняется относительная структура, а флаг --flatten складывает изображения в одну папку. Существующие файлы перезаписываются только с --force.
- Существующие файлы перезаписываются только с флагом --force.
Быстрый старт
python extract_images.py photos.zip --dest ./images
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python extract_images.py photos.zip --dest ./imagespython extract_images.py backup.tar.gz --dest ./images --min-size 10240python extract_images.py photos.zip --dest ./images --flatten --force
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
extract_images.py
#!/usr/bin/env python3
"""Извлечение изображений из zip или tar."""
from __future__ import annotations
import argparse
import shutil
import tarfile
import zipfile
from pathlib import Path, PurePosixPath, PureWindowsPath
def safe_parts(name: str) -> tuple[str, ...]:
normalized = name.replace("\\", "/")
path = PurePosixPath(normalized)
if path.is_absolute() or PureWindowsPath(normalized).drive:
raise ValueError(f"абсолютный путь: {name}")
parts = tuple(part for part in path.parts if part not in ("", "."))
if not parts or any(part == ".." for part in parts):
raise ValueError(f"небезопасный путь: {name}")
return parts
def image_extensions(value: str) -> set[str]:
result = set()
for item in value.split(","):
item = item.strip().lower()
if item:
result.add(item if item.startswith(".") else f".{item}")
return result
def main() -> int:
parser = argparse.ArgumentParser(description="Извлечь изображения из архива")
parser.add_argument("archive", type=Path, help="Zip или tar архив")
parser.add_argument("--dest", type=Path, default=Path("images"), help="Папка назначения")
parser.add_argument("--extensions", default="jpg,jpeg,png,gif,webp,bmp,tif,tiff,heic,avif", help="Список расширений")
parser.add_argument("--min-size", type=int, default=1, help="Минимальный размер файла")
parser.add_argument("--flatten", action="store_true", help="Сложить файлы в одну папку")
parser.add_argument("--force", action="store_true", help="Перезаписать существующие файлы")
parser.add_argument("--dry-run", action="store_true", help="Только показать план")
args = parser.parse_args()
archive_path = args.archive.expanduser().resolve()
destination = args.dest.expanduser().resolve()
if not archive_path.is_file():
parser.error(f"Архив не найден: {archive_path}")
wanted = image_extensions(args.extensions)
plan: list[tuple[str, Path, int]] = []
if zipfile.is_zipfile(archive_path):
with zipfile.ZipFile(archive_path) as archive:
for info in archive.infolist():
if info.is_dir() or info.flag_bits & 0x1 or info.file_size < args.min_size:
continue
if Path(info.filename).suffix.lower() not in wanted:
continue
try:
parts = (Path(info.filename).name,) if args.flatten else safe_parts(info.filename)
except ValueError as error:
print(f"Пропуск: {error}")
continue
target = destination.joinpath(*parts)
if target.resolve().is_relative_to(destination.resolve()):
plan.append((info.filename, target, info.file_size))
elif tarfile.is_tarfile(archive_path):
with tarfile.open(archive_path, mode="r:*") as archive:
for member in archive:
if not member.isfile() or member.size < args.min_size:
continue
if Path(member.name).suffix.lower() not in wanted:
continue
try:
parts = (Path(member.name).name,) if args.flatten else safe_parts(member.name)
except ValueError as error:
print(f"Пропуск: {error}")
continue
target = destination.joinpath(*parts)
if target.resolve().is_relative_to(destination.resolve()):
plan.append((member.name, target, member.size))
else:
print("Формат не распознан. Поддерживаются zip и tar.")
return 2
if not plan:
print("Изображения не найдены.")
return 0
existing = [str(target) for _, target, _ in plan if target.exists() and not args.force]
if existing:
print("Файлы уже существуют, добавьте --force:")
for name in existing[:20]:
print(f" {name}")
return 1
total = sum(size for _, _, size in plan)
print(f"Изображений: {len(plan)}, размер: {total / 1024 / 1024:.1f} МБ")
if args.dry_run:
for name, target, _ in plan:
print(f" {name} -> {target}")
print("Режим проверки: ничего не записано.")
return 0
destination.mkdir(parents=True, exist_ok=True)
if zipfile.is_zipfile(archive_path):
with zipfile.ZipFile(archive_path) as archive:
for name, target, _ in plan:
target.parent.mkdir(parents=True, exist_ok=True)
with archive.open(name) as source, target.open("wb") as handle:
shutil.copyfileobj(source, handle)
else:
with tarfile.open(archive_path, mode="r:*") as archive:
for name, target, _ in plan:
source = archive.extractfile(name)
if source is None:
continue
target.parent.mkdir(parents=True, exist_ok=True)
with source, target.open("wb") as handle:
shutil.copyfileobj(source, handle)
print(f"Извлечено изображений: {len(plan)} в {destination}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.