Skip to content

Instantly share code, notes, and snippets.

@aleroddepaz
Last active December 16, 2015 04:39
Show Gist options
  • Save aleroddepaz/5378731 to your computer and use it in GitHub Desktop.
Save aleroddepaz/5378731 to your computer and use it in GitHub Desktop.
Script to rename all the .mp3 files of a directory with a custom pattern. It uses the module eye3d. To find more information about it, check http://eyed3.nicfit.net/
import os
import re
import sys
import eyed3
def rename_songs(path, pattern):
if not check_arguments(path, pattern):
exit(1)
listdir = [os.path.join(path, f) for f in os.listdir(path)]
files = filter(os.path.isfile, listdir)
for filename in files:
rename_song(filename, path, pattern)
def check_arguments(path, pattern):
check = True
if not os.path.exists(path):
print("Directory '%s' does not exist" % path)
check = False
if not validate_pattern(pattern):
print("Incorrect pattern")
check = False
return check
def validate_pattern(pattern):
tag_fields = ['artist', 'album', 'title']
fields = re.findall('<(\w+)>', pattern)
diff = set(fields) - set(tag_fields)
return len(diff) == 0
def rename_song(filename, path, pattern):
try:
audiofile = eyed3.load(filename)
if audiofile is not None:
new_name = get_new_name(audiofile, pattern)
print("Renaming %s..." % new_name)
os.rename(filename, os.path.join(path, new_name))
except IOError:
print("IOError: Cannot rename file '%s'" % filename)
except OSError:
print("OSError: Cannot rename file '%s'" % filename)
def get_new_name(audiofile, pattern):
for field in re.findall('<(\w+)>', pattern):
attr = getattr(audiofile.tag, field)
pattern = pattern.replace('<' + field + '>', attr).strip()
return pattern + ".mp3"
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Incorrect number of arguments")
print("Usage: %s (directory) (pattern)" % os.path.basename(sys.argv[0]))
exit(1)
rename_songs(sys.argv[1], sys.argv[2])
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment