Created
August 17, 2024 16:53
-
-
Save azdanov/b45eaaedf113231ad4777db30b2e680f to your computer and use it in GitHub Desktop.
Rename enumerated mp4 and srt files in a directory from a names list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Module for renaming MP4 and SRT files based on names read from a text file.""" | |
import os | |
import re | |
from pathlib import Path | |
# Read names from the text file | |
with Path("names.txt").open("r") as f: | |
names = [line.strip() for line in f] | |
# Function to extract number from filename | |
def get_number(filename: str) -> int: | |
"""Extract the number from the filename and returns it as an integer.""" | |
return int(re.search(r"\d+", filename).group()) | |
# Get all mp4 files in the current directory and sort them by number in the filename | |
mp4_files = sorted([f for f in os.listdir() if f.endswith(".mp4")], key=get_number) | |
# Get all srt files in the current directory and sort them by number in the filename | |
srt_files = sorted([f for f in os.listdir() if f.endswith(".srt")], key=get_number) | |
# Rename mp4 files | |
for i, (old_name, new_name) in enumerate(zip(mp4_files, names), 1): | |
# Create new filename with index and name from text file | |
new_filename = f"{i}. {new_name}.mp4" | |
# Rename the file | |
Path(old_name).rename(new_filename) | |
print(f"Renamed '{old_name}' to '{new_filename}'") # noqa: T201 | |
# Rename srt files | |
for i, (old_name, new_name) in enumerate(zip(srt_files, names), 1): | |
# Create new filename with index and name from text file | |
new_filename = f"{i}. {new_name}.srt" | |
# Rename the file | |
Path(old_name).rename(new_filename) | |
print(f"Renamed '{old_name}' to '{new_filename}'") # noqa: T201 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment