Files
rename_anime_episodes/rename.py
2025-06-23 20:40:04 +07:00

60 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from sys import exit, argv
from os import listdir, rename
from os.path import splitext, realpath, exists
from re import search
patterns = [ # Паттерны для поиска номера эпизода
[r"\[\d+\]", 1, -1],
[r"[s]\d+[e]\d+", 4, None],
[r"[S]\d+[.][E]\d+", 5, None],
[r"\d+$", None, None],
# [r".\d+", None, None]
]
extensions = [".mkv", ".avi", ".mp4"] # Список поддерживаемых расширений
def rename_file(current_name, splitted, settedPath):
for pattern in patterns:
found_number = search(pattern[0], splitted[0]) # Ищем номер эпизода, если он есть то продолжаем
if found_number is None:
continue
found_number = found_number.group()[ pattern[1]:pattern[2] ]
new_name = "{:02d}{}".format(int(found_number), splitted[1]) # Новое имя файла
current_path = "{}\\{}".format(settedPath, current_name) if settedPath is not None else realpath(current_name) # Получаем путь до файла
new_path = "{}{}".format(current_path.replace(current_name, ""), new_name) # Новый путь до файла
rename(current_path, new_path) # Переименовываем файл
print("\"{}\" successfully renamed to \"{}\".".format(current_name, new_name))
break
def main(folder):
for file_name in listdir(folder):
splitted_name = splitext(file_name) # Разделяем имя файла и его расширение, итог: кортеж (0 - имя файла, 1 - расширение)
if splitted_name[1] in extensions: # Проверяем совпадения расширения со списком, если есть совпадения то переименовываем файл
rename_file(file_name, splitted_name, folder) # Вызываем функцию переименования файла
folder_input()
def folder_input():
folder = input("\nВведите путь до папки с эпизодами: ")
if exists(folder):
main(folder)
return
if (folder == "") and not exists(folder):
main(None)
return
folder_input()
if __name__ == '__main__':
try:
print("Чтобы оставить текущую директорию нажмите 'Enter'")
print("Чтобы выйти нажмите 'Ctrl + C'")
folder_input()
except KeyboardInterrupt:
exit()