from __future__ import with_statement
import os, os.path, sys
import fnmatch
from mutagen import easyid3, id3

def format(fname):
	try:
		eid3 = easyid3.EasyID3(fname)
	except id3.ID3NoHeaderError:
		eid3 = {}
	if "artist" in eid3 and "title" in eid3:
		return "%s - %s" % (eid3["artist"][0].encode("utf-8"), eid3["title"][0].encode("utf-8"))
	else:
		print >> sys.stderr, "Warning: file %r doesn't contain ID3 tags for artist and title, ignoring" % fname
		return None

try:
	topdir = sys.argv[1]
	with open(os.path.join(topdir, "mp3_songs.txt"), "w") as f:
		for top, dirs, files in os.walk(topdir):
			for fname in fnmatch.filter(files, "*.mp3"):
				line = format(os.path.join(top, fname))
				if line:
					print >> f, line
except Exception:
	sys.excepthook(*sys.exc_info())
raw_input("press enter to exit")
