Транслитерировать имена файлов
Переводит кириллицу в латиницу и делает имена переносимыми между системами, по умолчанию только показывает план.
Что делает скрипт
Скрипт заменяет русские, украинские и другие кириллические буквы устойчивыми латинскими сочетаниями, убирает небезопасные символы и сохраняет расширение. Файлы без кириллицы пропускаются. Переименование выполняется только после --apply.
- После переименования ссылки на файлы в других программах могут перестать работать.
Быстрый старт
python transliterate_names.py --dir ~/Documents --recursive
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python transliterate_names.py --dir ./docspython transliterate_names.py --dir ./docs --recursive --apply
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
transliterate_names.py
#!/usr/bin/env python3
"""Транслитерация кириллических имён файлов в латиницу."""
from __future__ import annotations
import argparse
import os
import re
import sys
import unicodedata
from pathlib import Path
TRANSLIT = {
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "yo",
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
"ф": "f", "х": "kh", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "shch",
"ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
"і": "i", "ї": "yi", "є": "ye", "ґ": "g",
}
CYRILLIC = re.compile(r"[А-Яа-яЁёІіЇїЄєҐґ]")
INVALID = re.compile(r"[^\w.\- ]", re.UNICODE)
def split_name(name: str) -> tuple[str, str, int]:
leading = len(name) - len(name.lstrip("."))
if leading >= len(name):
return "", "", 0
core = name[leading:]
suffix = Path(core).suffix
stem = core[: -len(suffix)] if suffix else core
return stem, suffix, leading
def transliterate(text: str) -> str:
result = []
for char in text:
mapped = TRANSLIT.get(char.lower())
if mapped is None:
result.append(char)
elif char.isupper() and mapped:
result.append(mapped.capitalize())
else:
result.append(mapped)
return "".join(result)
def transliterate_name(name: str) -> str:
stem, suffix, leading = split_name(name)
text = unicodedata.normalize("NFKC", transliterate(stem))
text = re.sub(r"\s+", "_", text)
text = INVALID.sub("", text)
text = re.sub(r"_+", "_", text).strip("._- ")
if not text:
text = "file"
suffix = INVALID.sub("", unicodedata.normalize("NFKC", suffix))
return "." * leading + text + suffix
def unique_path(path: Path, reserved: set[Path]) -> Path:
if path not in reserved and not path.exists():
return path
for index in range(2, 10000):
candidate = path.with_name(f"{path.stem}_{index}{path.suffix}")
if candidate not in reserved and not candidate.exists():
return candidate
raise RuntimeError(f"Не удалось подобрать имя для {path}")
def iter_files(root: Path, recursive: bool):
if recursive:
for current, dirs, names in os.walk(root):
current_path = Path(current)
dirs[:] = [name for name in dirs if not (current_path / name).is_symlink()]
for name in names:
path = current_path / name
if path.is_file() and not path.is_symlink():
yield path
else:
for path in root.iterdir():
if path.is_file() and not path.is_symlink():
yield path
def main() -> int:
parser = argparse.ArgumentParser(description="Транслитерировать имена файлов")
parser.add_argument("--dir", type=Path, required=True, help="Папка с файлами")
parser.add_argument("--recursive", action="store_true", 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}")
reserved: set[Path] = set()
plan: list[tuple[Path, Path]] = []
skipped = 0
for source in iter_files(root, args.recursive):
if not CYRILLIC.search(source.name):
skipped += 1
continue
new_name = transliterate_name(source.name)
if new_name == source.name:
skipped += 1
continue
destination = unique_path(source.with_name(new_name), reserved)
reserved.add(destination)
plan.append((source, destination))
if not plan:
print("Файлы с кириллицей не найдены.")
return 0
for source, destination in plan:
print(f"{source.relative_to(root)} -> {destination.name}")
if not args.apply:
print(f"\nПредпросмотр: {len(plan)} переименований. Для применения добавьте --apply.")
return 0
renamed = 0
failed = 0
for source, destination in plan:
try:
source.rename(destination)
renamed += 1
except OSError as error:
failed += 1
print(f"Ошибка {source}: {error}", file=sys.stderr)
print(f"\nПереименовано: {renamed}, пропущено: {skipped}, ошибок: {failed}")
return 0 if failed == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.