import os import re import shutil import mutagen from mutagen.easyid3 import EasyID3 # Change this to where your music is stored searchBases = [r'H:\Music',r'H:\Shared',r'C:\Music',r'C:\Shared'] # Change this to where you want to make the new, sorted collection newRoot = r'H:\NewMusic' # Change this to where you want the xml to be outputed xmlOut = r'H:\musicList.xml' # Change this to where you want the debug file to appear debugFile = r'H:\musicSorter.txt' # Dont change this artists = {} counter = {"artists":0,"albums":0,"tracks":0} resub = re.compile("[^a-zA-Z0-9 ]").sub def Debug(bug): f = file(debugFile,"a") f.write(bug) f.close() for dirBase in searchBases: for root, dirs, files in os.walk(dirBase): Debug(root) for fileName in files: if fileName.lower().endswith(".mp3"): try: id3 = EasyID3(root+os.sep+fileName) artist = resub(""," ".join(id3["artist"]).lower()).strip() album = resub(""," ".join(id3["album"]).lower()).strip() title = resub(""," ".join(id3["title"]).lower()).strip() if not artist in artists: artists[artist] = {} if not album in artists[artist]: artists[artist][album] = {} if not title in artists[artist][album]: artists[artist][album][title] = "" artists[artist][album][title] = root+os.sep+fileName except: Debug("%s Has no tag"%fileName) else: Debug("%s Is an invalid filetype"%fileName) print "Finished parsing %s"%dirBase print "Finished Parsing..." print "Creating Directory tree and copying tracks......." # Generate the structure lastFolder = "" for folder in newRoot.split(os.sep): lastFolder += folder+os.sep if not os.path.exists(lastFolder): os.mkdir(lastFolder) for artist in artists: counter["artists"] += 1 artistPath = newRoot+os.sep+artist.title() if not os.path.exists(artistPath): os.mkdir(artistPath) for album in artists[artist]: counter["albums"] += 1 albumPath = artistPath+os.sep+album.title() if not os.path.exists(albumPath): os.mkdir(albumPath) for track in artists[artist][album]: counter["tracks"] += 1 print "Coping %s | %s | %s"%(artist.title(),album.title(),track.title()) inFile = artists[artist][album][track] outFile = albumPath+os.sep+track.title()+".mp3" if not os.path.exists(outFile): shutil.copyfile(inFile,outFile) else: print outFile,"Exists, skipping..." print "Creating XML" xml = file(xmlOut,"w") # Write library info xml.write("
\n") xml.write("\n") xml.write(" %s\n"%counter["artists"]) xml.write(" %s\n"%counter["albums"]) xml.write(" %s\n"%counter["tracks"]) xml.write("\n") for artist in artists: xml.write("\n"%artist.title()) for album in artists[artist]: xml.write(" \n"%album.title()) for track in artists[artist][album]: xml.write(" %s\n"%track.title()) xml.write(" \n") xml.write("\n") xml.write("
\n") xml.close() print "Done" print "%s Tracks, %s Albums, %s Tracks"%(counter["artists"],counter["albums"],counter["tracks"])