Skip to content

Instantly share code, notes, and snippets.

@bemasher
Created December 2, 2010 00:46
Show Gist options
  • Save bemasher/724540 to your computer and use it in GitHub Desktop.
Save bemasher/724540 to your computer and use it in GitHub Desktop.
Uses tvrage.com's xml api to retrieve episode titles for a specific show and rename files accordingly.
import glob, os, urllib2, re
from xml.etree import ElementTree
# Input: Takes in "S##E##.avi" or "S##E##.mkv"
# Output: Renames to "S##E## - [Episode title].avi" (or mkv)
# Search: http://services.tvrage.com/feeds/search.php?show=Mythbusters for sid
show_id = 4605
# Get episode list from tvrage.com for the selected show
xml_data = urllib2.urlopen("http://services.tvrage.com/feeds/episode_list.php?sid=%d" % show_id).read()
xml_tree = ElementTree.fromstring(xml_data)
episodes = {}
# For each season in the xml tree
for season in xml_tree.findall("Episodelist/Season"):
# Get the season number
season_num = int(season.get("no"))
# For each episode in the episode list of the current season
for episode in season.findall("episode"):
# Get the episode number and title
episode_num = int(episode.find("seasonnum").text)
episode_title = episode.find("title").text
# Create the episode_code S##E##
episode_code = "S%02dE%02d" % (season_num, episode_num)
# Remove any illegal filename characters from the title
episodes[episode_code] = re.sub("[\\/<>:|?*]", "", episode_title)
# Build a list of video files in the current directory
file_list = []
for extension in ["*.avi", "*.mkv"]: # Add whatever extensions you desire here
file_list.extend(glob.glob(extension))
for file in file_list:
# Get the filename and extension
filename, extension = file.split(".")
# Build new filename
new_filename = filename + " - " + episodes.get(filename, "") + "." + extension
# Display proposed rename
print 'Renaming: "%s" -> "%s"' % (file, new_filename)
# Comment this out for a dry run, then if the output
# looks right uncomment and run to do actual rename
# os.rename(file, new_filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment