Файлы и папки

Сравнить две папки

Сравнивает две папки по относительным путям, размерам и при необходимости по SHA-256, ничего не меняя.

Python Windows macOS Linux Продвинутый
Скачать compare_directories.py
Описание

Что делает скрипт

Скрипт строит карту файлов для каждой папки, показывает отсутствующие и различающиеся файлы. В быстром режиме сравниваются размеры, с флагом --hash дополнительно считаются контрольные суммы. Это удобная проверка перед копированием или синхронизацией.

Запуск

Быстрый старт

python compare_directories.py --left ./old --right ./new --hash

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python compare_directories.py --left ./backup --right ./current
  • python compare_directories.py --left ./a --right ./b --hash --json diff.json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Исходник

compare_directories.py

#!/usr/bin/env python3
"""Сравнение двух каталогов по составу и содержимому файлов."""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path

DEFAULT_EXCLUDES = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv"}


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 build_map(root: Path, excludes: set[str]) -> dict[str, Path]:
    result = {}
    for path in iter_files(root, excludes):
        relative = str(path.relative_to(root)).replace(os.sep, "/")
        result[relative] = path
    return result


def file_hash(path: Path, chunk_size: int = 1024 * 1024) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(chunk_size):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser(description="Сравнить две папки")
    parser.add_argument("--left", type=Path, required=True, help="Первая папка")
    parser.add_argument("--right", type=Path, required=True, help="Вторая папка")
    parser.add_argument("--hash", action="store_true", help="Сравнивать SHA-256, а не только размер")
    parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    left = args.left.expanduser().resolve()
    right = args.right.expanduser().resolve()
    for label, root in (("левая", left), ("правая", right)):
        if not root.is_dir():
            parser.error(f"{label.capitalize()} папка не найдена: {root}")

    excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()}
    left_files = build_map(left, excludes)
    right_files = build_map(right, excludes)

    only_left = sorted(set(left_files) - set(right_files))
    only_right = sorted(set(right_files) - set(left_files))
    different = []
    same = 0

    for relative in sorted(set(left_files) & set(right_files)):
        left_path = left_files[relative]
        right_path = right_files[relative]
        try:
            left_size = left_path.stat().st_size
            right_size = right_path.stat().st_size
        except OSError as error:
            different.append({"path": relative, "reason": f"ошибка чтения: {error}"})
            continue
        if left_size != right_size:
            different.append(
                {"path": relative, "reason": "размер", "left": left_size, "right": right_size}
            )
            continue
        if args.hash:
            try:
                if file_hash(left_path) != file_hash(right_path):
                    different.append({"path": relative, "reason": "sha256"})
                    continue
            except OSError as error:
                different.append({"path": relative, "reason": f"ошибка чтения: {error}"})
                continue
        same += 1

    for relative in only_left:
        print(f"Только слева:  {relative}")
    for relative in only_right:
        print(f"Только справа: {relative}")
    for item in different:
        print(f"Отличается:    {item['path']} ({item['reason']})")

    print(
        f"\nСлева файлов: {len(left_files)}, справа: {len(right_files)}, "
        f"одинаковых: {same}, отличий: {len(only_left) + len(only_right) + len(different)}"
    )

    if args.json:
        output = args.json.expanduser()
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(
            json.dumps(
                {
                    "left": str(left),
                    "right": str(right),
                    "only_left": only_left,
                    "only_right": only_right,
                    "different": different,
                    "same": same,
                },
                ensure_ascii=False,
                indent=2,
            ) + "\n",
            encoding="utf-8",
        )
        print(f"Отчёт сохранён: {output}")

    return 1 if only_left or only_right or different else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get files-compare-directories
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Файлы и папки

Поиск, переименование, сортировка, сравнение и безопасная работа с файлами.