Here’s our little snippet of Python for the week. We need to rename some jpeg files from the cryptic emplid.jpg form supplied by the parking office to something a little easier for humans to parse, like Chapman_Ben.jpg. Here’s one way to do it, assuming that you’ve already managed to generate a list of emplid to name mappings by querying a database or Excel spreadsheet or what have you.
#!/usr/bin/env python ''' Ben Chapman - Thu Oct 21 15:51:49 EDT 2010 Super basic script to rename some files from emplid.JPG to Lastname_Firstname.jpg Directory is full of *.JPG files and a file, dumped from a database query, called 'names.txt'. It has the following layout: EMPLIDtFULL_NAMEn 234234234tBunny,Bugsn 234123323tPark Smith,Jasonn 111111111tGarcia-Morales,Gilbertn 222222222tVon Trapp Family,Singern We want to copy from 2222222222.JPG to Von_Trapp_Family_Singer.jpg ''' import shutil DEBUG = False names = open('names.txt','rb').readlines() # Dump the header row names = names[1:] for name in names: # Split on tabs oldname,newname = name.split('t') # Get rid of trailing newline if present newname = newname.rstrip() # Commas to underscores newname = newname.replace(',','_') # Spaces to underscores newname = newname.replace(' ','_') try: # shutil.copyfile will fail if original file # doesn't exist, so wrapped in a try block. if DEBUG: print "oldname: %s newname: %s" % (oldname, newname) else: shutil.copyfile(oldname + '.JPG',newname+'.jpg') except IOError: pass