A little Python: renaming multiple files based on content

This one really doesn’t deserve its own post – but here you are anyway. Imagine that you’ve had to download a bunch of files from your institution’s ERP system – because of the way your browser and their web page interact, you now have a series of CSV files with names like this:


You want to rename them something more useful based on the contents of the file, like 5039-netids.csv, 5041-netids.csv … 5109-netids.csv.

Here’s one way to accomplish that with a minimum of fuss. It relies on the fact that the data provides you with the target filename; for example, the first few lines of one of the files looks something like this:

"ID","Name","Term","Career","Prim Prog","Exp Grad"

The goal is to save the input file back out as 5059-netids.csv. You can see the “5059” in the third field of the second line of the data. We’ll use the shutil and glob modules. We’re going to create a list of all of the files that we downloaded. Then we’re going to iterate over the list, opening each file. For each file, we read the first line, which contains header information, and throw it away. Then we read the next line; we split the line into a list of elements. We pick out the third element to use as part of the target file name. Now we use shutil.move to move the old file to the new file. Here’s the script:

import glob
import shutil

filenames = glob.glob("EU_SR*.csv")

for f in filenames:
    currfile = open(f,'rb')
    header = currfile.readline()
    data = currfile.readline()
    fields = data.split('","')
    shutil.move(f, fields[2] + "-netids.csv")

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