Skip to content

Instantly share code, notes, and snippets.

@brunomlopes
Created January 24, 2010 00:52
Show Gist options
  • Save brunomlopes/284901 to your computer and use it in GitHub Desktop.
Save brunomlopes/284901 to your computer and use it in GitHub Desktop.
point script to directory with mismatched filenames, it should clean them up a bit
#!/usr/bin/python26
import os,re,sys
from pprint import pprint
expressions = ["(?P<title>[a-zA-Z0-9\-.]+)\.[sS ](?P<season>[0-9]+)[eE ](?P<episode>[0-9]+)\.(?P<rest>[a-zA-Z0-9.()\-\[\] ]*)\.avi",
"(?P<title>[a-zA-Z0-9\-.]+)\.(?P<season>[0-9]+)(?P<episode>[0-9]{2})\.(?P<rest>[a-zA-Z0-9.()\-\[\] ]*)\.avi",
"(?P<title>[a-zA-Z0-9\-.]+)[ _]*[-. ][_ ]*(?P<season>[0-9]+)x(?P<episode>[0-9]{2})[ ]*[-.][ ]*(?P<rest>[a-zA-Z0-9.()\-\[\] ]*)\.avi"]
expressions = expressions + [e.replace("avi","srt") for e in expressions] + [e.replace("avi","mkv") for e in expressions]
compiledExpressions= [re.compile(e) for e in expressions]
if len(sys.argv) > 1:
directory = sys.argv[1]
else:
directory = "lost"
title = None
if len(sys.argv) > 2:
title = sys.argv[2]
print "using %s as directory" % directory,
if title:
print " and %s as title" % title
else:
print
fileFormat = "%(title)s.S%(season).2dE%(episode).2d%(rest)s%(extension)s"
rename = True
for file in [f for f in os.listdir(directory) if f.endswith("avi") or f.endswith("srt") or f.endswith("mkv")]:
print file
for exp in compiledExpressions:
match = exp.match(file)
if not match:
continue
match = match.groupdict()
for k in ["episode","season"]:
try:
match[k] = int(match[k])
except ValueError:
pass
match["extension"] = os.path.splitext(file)[-1]
match["title"] = ".".join([a.capitalize() for a in match["title"].split(".")])
if not match["rest"].startswith(".") and match["rest"] != "":
match["rest"] = "."+match["rest"]
if "season" in match and "episode" in match and "title" in match:
if title != None:
match["title"] = title
newFileName = os.path.join(directory, (fileFormat % match))
print "Renaming to %s " % newFileName
if rename:
os.rename(os.path.join(directory,file),newFileName)
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment