reading id3 tags with python

jeff jeffrey.aylesworth at gmail.com
Thu Nov 23 19:36:06 EST 2006


i stated using a python module called id3reader
(http://www.nedbatchelder.com/code/modules/id3reader.html) and i tried
to use it to organize all my music files (right now they are all in one
folder (i want them in Music/artist/album/title.mp3)) but im getting an
error with the code, however it does seem to be from the id3 library,
and not from /my/ code, so if somebody knows how to fix this problem,
or even if somebody knows of a better id3 library please tell me.

my code::
#############################################
#! /usr/bin/python
import id3reader as id3
from glob import *
import sys, os
#from shutil import *

if len(sys.argv) >= 2:
  location = sys.argv[1]
else:
  location = '../'

files = glob(location + "*.mp3")

print "\n\n"
print "Welcome to the MP3 renamer"
print "files following this pattern will be changed::"
print location + "*.mp3"
print str(len(files)) + " will be affected"
Continue = True
while Continue == True:
  x = raw_input("\tContinue?(y/n)")
  if x=='y' or x=='n':
    if x=='y':
      print "continueing..."
    Continue = False
#################################
for file in files:
  info = id3.Reader(file)
  data = {}
  data['artist'] = info.getValue('performer')
  if data['artist'] == None:
    data['artist'] = "Unknown Artist"
  data['album'] = info.getValue('album')
  if data['album'] == None:
    data['album'] = "Unknown Album"
  data['title'] = info.getValue('title')

  try:
    os.mkdir(data['artist'])
    os.mkdir(data['artist'] + '/' + data['album'])
  except OSError:
    print "directory already exists...continueing anyways"

  #print data
  new_file = data['artist'] + '/' + data['album'] + '/' + data['title']
+ '.mp3'
  os.rename(file,new_file)

print "\n\n"
#############################################
for those of you who dont understand this, ill try to explain my best
here::
lines::
1) shebang (telling linux to use python)
2-5) imports (shutils was commented out -- i was using this before, but
now im not)
7-10) finding out the directory to find the music in
12) getting a tuple of all the files in the directory it's looking in
with the extension mp3
14-25) making sure you realy want to do this
27-end) for each file::
  27-36) getting all the id3 info and storing it in a dictionary
  38-42) tries to make the directories (try will make sure no error is
shown if they already exist)
  45-46) renames he file, into the new directory




More information about the Python-list mailing list