## songsort.py -- A small Python-script for adding track numbers to filenames. ## The track-numbers are determined from the time stamps of the MP3-files, ## with track 01 presumably having been saved before track 02, etc. ## Coded by N. Xnegghara May 2006 and placed into Public Domain. ## Example usage: ## from songsort import * ## os.chdir('../Taraf-~1') ## add_tracknumbers('.','mp3','Taraf de Haidouks Vol 1 - ') ## os.chdir('../Taraf-~2') ## add_tracknumbers('.','mp3','Taraf de Haidouks Vol 2 - ') ## os.chdir('../Piazzo~1') ## add_tracknumbers('.','mp3','Piazzolla - Burton - The New Tango - ') import os import re def sortbytime(a,b): '''Sorts two tuples a and b by their first element.''' (atime,aname) = a (btime,bname) = b if(atime < btime): return(-1) elif(atime > btime): return(+1) else: return(0) def second(p): '''Returns the second element of a pair-tuple.''' (a,b) = p return(b) def listdir_by_time(path,suff): '''List all files ending with "suff" in directory "path" sorted by their creation time''' olddir = os.getcwd() os.chdir(path) allfiles = os.listdir('.') sufflen = len(suff) files = map(lambda(fn): (os.stat(fn).st_mtime,fn), filter(lambda(s): (suff == s[-sufflen:]),allfiles) ) os.chdir(olddir) files.sort(sortbytime) return(map(second,files)) def twodigitrepr(n): '''Represent n with two digits, at least.''' s = repr(n) if(len(s) < 2): return('0' + s) else: return(s) def add_prefixes(prefix,names): '''Adds a prefix onto the front of each name in the given list.''' return(map(lambda(n): prefix+n, names)) def add_count_prefixes(names): '''Adds a running count 01, 02, ... in the front of each name in the given list.''' return([twodigitrepr(i+1)+names[i] for i in range(len(names))]) def add_tracknumbers(path,suff,pref1): '''Do the thing.''' oldnames = listdir_by_time(path,suff) newnames = add_prefixes(pref1,add_count_prefixes(add_prefixes('-',oldnames))) while(oldnames): os.rename(oldnames.pop(),newnames.pop()) ## Use like this: ## rename_by_pattern('.','mp3','Kremer - From My Home','Tsitsanis - Hommage a Tsitsanis') def rename_by_pattern(path,suff,oldpat,newpart): '''Correct your mistakes.''' substpat = re.compile(oldpat) oldnames = listdir_by_time(path,suff) for oldname in oldnames: newname = substpat.sub(newpart,oldname) if(newname): os.rename(oldname,newname)