Skip to content

Instantly share code, notes, and snippets.

@storborg
Created October 16, 2009 23:53
Show Gist options
  • Select an option

  • Save storborg/212159 to your computer and use it in GitHub Desktop.

Select an option

Save storborg/212159 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import os.path
import id3reader
import re
SRC_ROOT = '/Users/Shared/Music'
DST_ROOT = '/Users/Shared/Music-sorted'
def move_song(src, dst):
try:
os.makedirs(os.path.dirname(dst))
except OSError:
pass
os.rename(src, dst)
progress = 0
for root, dirs, files in os.walk(SRC_ROOT):
for f in [os.path.join(root, fname) for fname in files]:
if f.lower().endswith('.mp3'):
# Parse this song... first try to get ID3 tag data.
progress += 1
id3r = id3reader.Reader(f)
artist = id3r.getValue('performer')
if artist is None:
artist = "Unknown"
album = id3r.getValue('album')
if album is None:
album = "Unknown"
title = id3r.getValue('title')
if title is None:
print "********************************"
title = "Unknown - " + os.path.basename(f)[:-3]
track = id3r.getValue('track')
if track is None:
pass
else:
if '/' in track:
track = track.split('/')[0]
try:
track = int(track)
except ValueError:
pass
else:
title = "%02d %s" % (track, title)
title = title[:32]
new_path = os.path.join(DST_ROOT, artist, album, title + '.mp3')
print "%d - Renaming %s to %s" % (progress, repr(f), repr(new_path))
move_song(f, new_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment