Переименовать фотографии по дате съёмки
Читает EXIF-дату съёмки и переименовывает фото в стабильный формат, по умолчанию только показывает план.
Что делает скрипт
Скрипт открывает JPEG, TIFF и другие изображения через Pillow, берёт DateTimeOriginal или резервные теги и формирует имя вида 2025-04-18_14-30-05.jpg. При отсутствии EXIF файл пропускается, если не указан --use-mtime. Переименование выполняется только с флагом --apply.
- Перед применением проверьте предпросмотр: имена меняются необратимо без резервной копии.
Быстрый старт
python rename_by_exif_date.py --dir ~/Photos --apply
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python rename_by_exif_date.py --dir ~/Photospython rename_by_exif_date.py --dir ~/Photos --recursive --prefix img_ --apply
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install Pillow
python3 -m pip install Pillow
python3 -m pip install Pillow
rename_by_exif_date.py
#!/usr/bin/env python3
"""Переименование изображений по дате съёмки из EXIF."""
from __future__ import annotations
import argparse
import os
import sys
from datetime import datetime
from pathlib import Path
try:
from PIL import Image
except ImportError:
Image = None
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".tif", ".tiff", ".png", ".webp"}
EXIF_TAGS = (36867, 36868, 306)
def read_taken_at(path: Path) -> datetime | None:
with Image.open(path) as image:
exif = image.getexif()
for tag in EXIF_TAGS:
value = exif.get(tag)
if value is None:
continue
if isinstance(value, bytes):
value = value.decode("utf-8", errors="ignore")
text = str(value).strip().replace("\x00", "")
for fmt in ("%Y:%m:%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"):
try:
return datetime.strptime(text[:19], fmt)
except ValueError:
continue
return None
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, files in os.walk(root):
dirs[:] = [name for name in dirs if not (Path(current) / name).is_symlink()]
for name in files:
yield Path(current) / name
else:
yield from root.iterdir()
def main() -> int:
parser = argparse.ArgumentParser(description="Переименовать фото по дате EXIF")
parser.add_argument("--dir", type=Path, required=True, help="Папка с изображениями")
parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки")
parser.add_argument("--prefix", default="", help="Префикс нового имени")
parser.add_argument("--use-mtime", action="store_true", help="Использовать дату файла, если EXIF нет")
parser.add_argument("--apply", action="store_true", help="Выполнить переименование")
args = parser.parse_args()
if Image is None:
print("Нужен Pillow: python3 -m pip install Pillow", file=sys.stderr)
return 2
root = args.dir.expanduser().resolve()
if not root.is_dir():
parser.error(f"Папка не найдена: {root}")
planned = []
skipped = []
reserved: set[Path] = set()
for path in iter_files(root, args.recursive):
if not path.is_file() or path.is_symlink():
continue
if path.suffix.lower() not in IMAGE_EXTENSIONS:
continue
try:
taken = read_taken_at(path)
except Exception as error:
skipped.append((path, f"не удалось прочитать EXIF: {error}"))
continue
if taken is None:
if not args.use_mtime:
skipped.append((path, "нет даты EXIF"))
continue
taken = datetime.fromtimestamp(path.stat().st_mtime)
new_name = f"{args.prefix}{taken:%Y-%m-%d_%H-%M-%S}{path.suffix.lower()}"
destination = unique_path(path.with_name(new_name), reserved)
reserved.add(destination)
planned.append((path, destination, taken))
if not planned:
print("Нечего переименовывать.")
for path, reason in skipped:
print(f"Пропуск {path.name}: {reason}")
return 0
for source, destination, taken in planned:
action = "Переименовать" if args.apply else "Будет переименован"
print(f"{action}: {source.relative_to(root)} -> {destination.name} ({taken:%Y-%m-%d %H:%M:%S})")
if not args.apply:
print(f"\nПредпросмотр: {len(planned)} файлов. Для применения добавьте --apply.")
return 0
done = 0
for source, destination, _ in planned:
try:
source.rename(destination)
done += 1
except OSError as error:
print(f"Ошибка {source}: {error}", file=sys.stderr)
print(f"\nПереименовано: {done}, пропущено: {len(skipped)}")
return 0 if done == len(planned) else 1
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.