A little bit of Python: copy files, parsing a tab-delimited file

Inside the cable car museum
Image by benjamin.chapman via Flickr

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
Enhanced by Zemanta
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s