Skip to content

Instantly share code, notes, and snippets.

@KL-7
Created June 1, 2012 19:23
Show Gist options
  • Save KL-7/2854547 to your computer and use it in GitHub Desktop.
Save KL-7/2854547 to your computer and use it in GitHub Desktop.
Fill track album sort order for iTunes
#!/usr/bin/env python
import logging
import sys
from os import path
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3NoHeaderError
totalfiles = 0
def error(err):
logging.basicConfig(filename="error.log", level=logging.ERROR, filemode='w')
logging.error(err)
def gettag(audio, tagname):
taglist = audio.get(tagname, None)
if taglist:
return taglist[0]
else:
return ""
def fill_tsoa(fpath):
audio = EasyID3(fpath)
artist = gettag(audio, "artist")
if not artist:
error("Missing artist in %s" % fpath)
album = gettag(audio, "album")
if not album:
error("Missing album in %s" % fpath)
year = gettag(audio, "date")
if not year:
error("Missing year in %s" % fpath)
tsoa = "%s -- %s - %s" % (artist, year, album)
audio["albumsort"] = tsoa
audio.save()
def fill_rec(root):
def process(arg, dirname, fnames):
for fname in fnames:
fname = fname.decode("cp1251")
name, ext = path.splitext(fname)
fname = path.join(dirname, fname)
if path.isfile(fname) and ext.lower() == ".mp3":
try:
fill_tsoa(fname)
global totalfiles
totalfiles = totalfiles + 1
print fname
except ID3NoHeaderError:
error("No tags in %s" % fname)
path.walk(root, process, None)
if __name__ == "__main__":
if sys.argv[1:]:
for dirname in sys.argv[1:]:
fill_rec(dirname)
else:
fill_rec(".")
print "\nTotal files: %d" % totalfiles
raw_input();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment