#!/usr/bin/env pythonimport osimport shutilimport reimport ptab"""Sort By Artist.pyChanges for 2.0:* RENAMES FILES! Now songs are moved to Artist/Title.ptb as defined in their header.* Script was refactored. Slightly* Added optimizations (check for unknown folder EVERY FILE? Nope.)* Alleviated that cascade thing that was going on. (I thought it was kind of pretty but still, it hurts)* Took advantage of ptab.ReadHeader throwing an exception* RESPONSIBLE EXCEPTION HANDLING"""path = os.path.abspath('.')DANGEROUS_CHARACTERS = re.compile('[/\?<>:"\\|*]')UnknownDir = os.path.join(path,"Unknown")if not(os.path.exists(UnknownDir)): os.mkdir("Unknown")def cleanFilename(oldName): newName = re.sub(DANGEROUS_CHARACTERS, '', oldName) return newNamefor file in os.listdir('.'): if file.endswith('.ptb'): # try loading the .ptb file try: tabInfo = ptab.ReadHeader(file) except (IOError): print("'%s' is either corrupted or not a powertab file." %(file)) #os.system('pause') continue # prepare the artist subdirectory Artist = tabInfo['Artist'] ArtistDir = "" if Artist: Artist = cleanFilename(Artist) ArtistDir = os.path.join(path,Artist) # create a new directory if it doesn't exist if not os.path.isdir(ArtistDir): try: os.mkdir(Artist) except: print("Could not create folder for '%s'" %(Artist)) continue else: ArtistDir = UnknownDir # Rename the file to the song's title Title = tabInfo['Title'] if Title: Title = cleanFilename(Title) newName = Title + ".ptb" os.rename(file, newName) file = newName #finally,ready to move the file shutil.move(file, ArtistDir)