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:
EU_SR_LAW_NETIDS.csv EU_SR_LAW_NETIDS (1).csv ... EU_SR_LAW_NETIDS (14).csv
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" "1111","Bunny,Bugs","5059","LAW","LLM","5069" "2222","Duck,Daffy","5059","LAW","JD","5089"
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() currfile.close() fields = data.split('","') shutil.move(f, fields + "-netids.csv")