Skip to content

Instantly share code, notes, and snippets.

@kionay
Last active September 29, 2018 04:35
Show Gist options
  • Save kionay/e10b826f8376977b44b86126167f56a1 to your computer and use it in GitHub Desktop.
Save kionay/e10b826f8376977b44b86126167f56a1 to your computer and use it in GitHub Desktop.
A script to rename all media files in a given directory to one more suitable for Plex Media Server
"""os, for file IO"""
import os
import re
import argparse
def files(path):
""" Returns a list of filenames from the given directory.
https://stackoverflow.com/questions/14176166/list-only-files-in-a-directory
"""
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
yield file # filename as string
def build_associations_dictionary(filenames):
"""Builds a dictionary from a list of filenames.
The keys are the season and episode identifying strings.
example: {"S01E01":"/path/to/title.S01E01.mp4"}
"""
number_regex = r"s\d{1,2}e\d{1,2}"
compiled_number_regex = re.compile(
number_regex, re.MULTILINE | re.IGNORECASE)
associations = {}
for filename in filenames:
episode_search = compiled_number_regex.findall(filename)
if episode_search:
associations[episode_search[0]] = filename
return associations
def get_args():
"""Sets up command-line arguments. Returns the parsed arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("directory",
type=str,
help="The directory containing the media files to be renamed. Ignores trailing slahes.")
parser.add_argument("title",
type=str,
help="The title of the media to be renamed.")
args = parser.parse_args()
return args
def main():
"""The primary or controlling function."""
args = get_args()
working_directory = os.path.abspath(args.directory)
if not os.path.isdir(working_directory):
print("The path provided is not a directory.")
exit()
files_in_directory = [file for file in files(working_directory)]
media_associations = build_associations_dictionary(files_in_directory)
for key in media_associations:
title = args.title
episode_identifier = key
old_filename = media_associations[key]
_, file_extension = os.path.splitext(old_filename)
new_filename = f"{title} {episode_identifier}{file_extension}"
new_filepath = os.path.join(args.directory, new_filename)
old_filepath = os.path.join(args.directory, old_filename)
os.rename(old_filepath, new_filepath)
if __name__ == "__main__":
main()
@kionay
Copy link
Author

kionay commented Sep 29, 2018

Moved the regex inside the only function that uses it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment