Копировать с сохранением структуры
Копирует файлы в другую папку с сохранением относительных путей, по умолчанию работает в режиме предпросмотра.
Что делает скрипт
Скрипт обходит источник, при необходимости фильтрует файлы по расширениям и повторяет дерево каталогов в приёмнике. Существующие файлы по умолчанию пропускаются, перезапись требует флага --overwrite и подтверждения. Копирование выполняется только с --apply.
- Копирование может перезаписать файлы при --overwrite. Проверьте предпросмотр.
Быстрый старт
python copy_preserve_structure.py --src ./photos --dst /backup/photos --apply
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python copy_preserve_structure.py --src ./photos --dst /backup/photospython copy_preserve_structure.py --src . --dst /backup/project --ext .py --ext .md --apply
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
copy_preserve_structure.py
#!/usr/bin/env python3
"""Копирование файлов с сохранением относительной структуры."""
from __future__ import annotations
import argparse
import os
import shutil
import sys
import tempfile
from pathlib import Path
DEFAULT_EXCLUDES = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv"}
def human_size(size: int) -> str:
value = float(size)
for unit in ("B", "KB", "MB", "GB", "TB"):
if value < 1024 or unit == "TB":
return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024
return f"{size} B"
def iter_files(root: Path, excludes: set[str]):
for current, dirs, files in os.walk(root):
current_path = Path(current)
dirs[:] = [
name for name in dirs
if name not in excludes and not (current_path / name).is_symlink()
]
for name in files:
path = current_path / name
if path.is_symlink() or not path.is_file():
continue
yield path
def copy_one(source: Path, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
handle, temporary = tempfile.mkstemp(prefix=".copy-", dir=destination.parent)
os.close(handle)
try:
shutil.copy2(source, temporary)
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def main() -> int:
parser = argparse.ArgumentParser(description="Копировать файлы с сохранением структуры")
parser.add_argument("--src", type=Path, required=True, help="Источник")
parser.add_argument("--dst", type=Path, required=True, help="Приёмник")
parser.add_argument("--ext", action="append", default=[], help="Копировать только эти расширения")
parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить")
parser.add_argument("--apply", action="store_true", help="Выполнить копирование")
parser.add_argument("--overwrite", action="store_true", help="Разрешить перезапись существующих файлов")
parser.add_argument("--yes", action="store_true", help="Не задавать вопрос при перезаписи")
args = parser.parse_args()
source = args.src.expanduser().resolve()
destination = args.dst.expanduser().resolve()
if not source.is_dir():
parser.error(f"Источник не найден: {source}")
if destination == source or source in destination.parents:
parser.error("Приёмник не должен находиться внутри источника")
extensions = {
(part.strip() if part.strip().startswith(".") else "." + part.strip()).lower()
for value in args.ext
for part in value.split(",")
if part.strip()
}
excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()}
files = list(iter_files(source, excludes))
if extensions:
files = [path for path in files if path.suffix.lower() in extensions]
if not files:
print("Нет файлов для копирования.")
return 0
plan = []
overwrites = []
for path in files:
relative = path.relative_to(source)
target = destination / relative
if target.exists():
if not args.overwrite:
plan.append((path, target, "пропуск: уже существует"))
continue
overwrites.append(target)
plan.append((path, target, "перезаписать" if target.exists() else "копировать"))
for source_path, target, action in plan:
print(f"{action}: {source_path.relative_to(source)} -> {target}")
if not args.apply:
print(f"\nПредпросмотр: {len(plan)} файлов. Для копирования добавьте --apply.")
return 0
if overwrites and not args.yes:
if not sys.stdin.isatty():
parser.error("Нужно подтверждение перезаписи. Добавьте --yes")
answer = input(f"Перезаписать файлов: {len(overwrites)}. Введите yes: ").strip().lower()
if answer not in {"yes", "да"}:
print("Отменено.")
return 1
copied = 0
skipped = 0
failed = 0
for source_path, target, _ in plan:
if target.exists() and not args.overwrite:
skipped += 1
continue
try:
copy_one(source_path, target)
copied += 1
except OSError as error:
failed += 1
print(f"Ошибка {source_path}: {error}", file=sys.stderr)
print(f"\nСкопировано: {copied}, пропущено: {skipped}, ошибок: {failed}")
return 0 if failed == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.