Найти файлы с одинаковым именем
Находит одинаковые имена файлов в разных папках и показывает все пути, чтобы разобраться с коллизиями.
Что делает скрипт
Скрипт обходит дерево и группирует файлы по имени, по умолчанию без учёта регистра. Минимальное число вхождений настраивается. Так удобно искать конфликтующие index.html, README.md или одноимённые фотографии перед слиянием каталогов.
Быстрый старт
python find_same_name.py --dir ./projects --min-count 2
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python find_same_name.py --dir . --min-count 2python find_same_name.py --dir ~/Photos --case-sensitive --json names.json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
find_same_name.py
#!/usr/bin/env python3
"""Поиск файлов с одинаковыми именами в разных каталогах."""
from __future__ import annotations
import argparse
import json
import os
from collections import defaultdict
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 main() -> int:
parser = argparse.ArgumentParser(description="Найти файлы с одинаковыми именами")
parser.add_argument("--dir", type=Path, default=Path("."), help="Папка для поиска")
parser.add_argument("--min-count", type=int, default=2, help="Минимальное число файлов в группе")
parser.add_argument("--case-sensitive", action="store_true", help="Учитывать регистр имени")
parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить")
parser.add_argument("--json", type=Path, help="Сохранить результат в JSON")
args = parser.parse_args()
if args.min_count < 2:
parser.error("--min-count должен быть не меньше 2")
root = args.dir.expanduser().resolve()
if not root.is_dir():
parser.error(f"Папка не найдена: {root}")
excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()}
groups: dict[str, list[Path]] = defaultdict(list)
for path in iter_files(root, excludes):
key = path.name if args.case_sensitive else path.name.lower()
groups[key].append(path)
found = []
for key, paths in groups.items():
if len(paths) < args.min_count:
continue
found.append(
{
"name": paths[0].name,
"key": key,
"count": len(paths),
"files": [str(path.relative_to(root)) for path in sorted(paths)],
}
)
if not found:
print("Одинаковые имена не найдены.")
return 0
found.sort(key=lambda item: (-item["count"], item["key"]))
for group in found:
print(f"\n{group['name']} - {group['count']} файлов")
for relative in group["files"]:
print(f" {relative}")
print(f"\nГрупп: {len(found)}")
if args.json:
output = args.json.expanduser()
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(
json.dumps({"root": str(root), "groups": found}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(f"Отчёт сохранён: {output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.