#! /usr/bin/env python # This script is for taking a directory full of music files that start with a # track number and changing the number of each file by the specified positive # or negative amount. Useful for taking mp3 files from a 2-disc set and # putting them in order into a single directory. # # Distributed under the terms of the Gnu General Public License. See # www.gnu.org for more details. import sys, os, re #------------------------------------------------------------------------------# def init(): global num, action if (len(sys.argv) < 2) or (sys.argv[1] in ('-h', '--help')): show_usage() # get the num and figure out if we're adding or subtracting num = sys.argv[1] action_re = re.compile("^(\+|-)+(\d+)$") m = action_re.match(num) if m is None: sys.exit("n must be a number, preceded with + or -") action = ("+", "-")[m.group(1) == "-"] num = int(m.group(2)) if len(sys.argv) > 2: dir = sys.argv[2] else: dir = '.' if not os.path.isdir(dir): sys.exit(dir + " is not a directory. shame on you.") if dir != '.': os.chdir(dir) #------------------------------------------------------------------------------# def main(): # loop through the files and rename them if appropriate files = os.listdir('.') file_re = re.compile("^(\d{1,})(.*)") for file in files: if not os.path.isfile(file): continue m = file_re.match(file) if m is None: continue tracknum = int(m.group(1)) if action is "+": tracknum = tracknum + num elif action is "-": tracknum = tracknum - num # keep them from going to negative track numbers if tracknum < 0: sys.exit("this would yield negative track numbers. quitting.") tracknum = repr(tracknum) if len(tracknum) == 1: tracknum = "0" + tracknum newfile = tracknum + m.group(2) os.rename(file, newfile) print "renamed " + file + " to " + newfile #------------------------------------------------------------------------------# def show_usage(): usage = "usage: tracknum (+|-)n [directory]" sys.exit(usage) #------------------------------------------------------------------------------# init() main()