Sort music files into artist directories

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
MP3sort
=======

Sort music files by trying to extract the artist name from
each filename in the directory and moving the file to a new
subdirectory with the artist's name.

Feel free to change the file extension mask and artist
search pattern to fit your needs.

:Copyright: 2004-2008 Jochen Kupperschmidt
:Date: 13-Nov-2008
:License: MIT
"""

from glob import iglob
import os
import re


EXTENSION = 'mp3'
PATTERN = re.compile('(.+) - .*')

if __name__ == '__main__':
    # Get all filenames with the given extension.
    filenames = filter(os.path.isfile, iglob('*.' + EXTENSION))
    for filename in filenames:
        try:
            # Extract artist name from filename.
            dirname = PATTERN.match(filename).group(1).strip()
        except AttributeError:
            pass
        else:
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            os.rename(filename, os.path.join(dirname, filename))