#!/usr/bin/env python3 """Сортировка файлов из папки по категориям.""" from __future__ import annotations import argparse import shutil from collections import Counter from pathlib import Path CATEGORIES = { "images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".svg", ".heic", ".avif"}, "documents": {".pdf", ".doc", ".docx", ".txt", ".md", ".rtf", ".odt", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"}, "video": {".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".wmv"}, "audio": {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus"}, "archives": {".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".zst"}, "code": {".py", ".js", ".ts", ".html", ".css", ".json", ".yaml", ".yml", ".sh", ".ps1", ".bat", ".rs", ".go", ".java"}, } def category_for(path: Path) -> str: suffix = path.suffix.lower() for category, extensions in CATEGORIES.items(): if suffix in extensions: return category return "other" def unique_path(path: Path) -> Path: if not path.exists(): return path for index in range(2, 10000): candidate = path.with_name(f"{path.stem}_{index}{path.suffix}") if not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {path}") def main() -> int: parser = argparse.ArgumentParser(description="Разложить файлы по типам") parser.add_argument("--dir", type=Path, required=True, help="Папка с файлами") parser.add_argument("--unknown", default="other", help="Папка для неизвестных типов") parser.add_argument("--apply", action="store_true", help="Выполнить перемещение") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") if "/" in args.unknown or "\\" in args.unknown or args.unknown in {"", ".", ".."}: parser.error("--unknown должен быть простым именем папки") files = [path for path in root.iterdir() if path.is_file() and not path.is_symlink()] if not files: print("В папке нет файлов для сортировки.") return 0 planned = [] for path in files: category = args.unknown if category_for(path) == "other" else category_for(path) destination = unique_path(root / category / path.name) planned.append((path, destination, category)) counts = Counter(category for _, _, category in planned) for source, destination, _ in planned: print(f"{source.name} -> {destination.relative_to(root)}") if not args.apply: print(f"\nПредпросмотр: {len(planned)} файлов, категорий: {len(counts)}. Для применения добавьте --apply.") return 0 moved = 0 for source, destination, _ in planned: try: destination.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(source), str(destination)) moved += 1 except OSError as error: print(f"Ошибка {source}: {error}") print(f"\nПеремещено: {moved} из {len(planned)}") return 0 if moved == len(planned) else 1 if __name__ == "__main__": raise SystemExit(main())