How to batch change file names?

If you need to change a lot of file names with certain conditions, the work I did recently might be of some help.

Basically, I needed to add the ID in the tables (Fig.1) to the files as prefix in the folder (Fig.2) according to the location information in the filename. For example, the location information in the first file in fig.2 is "[1,9,B]". It means that I need added the ID# in of column = "B" and row = "9" , which is "76". The filenames after changing is shown in fig.3.

csv_sc.PNG Fig.1: spreadsheet with ID and locations.

before.PNG Fig.2: what filenames look like before change.

after.PNG Fig.3: what filenames look like after changing.

My strategy

I used python os module and csv module to do this job.

  • First, I read the ID list into a dictionary called ID_dict.
  • Then read the location information from the filename.
  • Finally add the ID as a prefix to the target filename.
In [ ]:
import os
import csv

# locate to target directory
os.chdir('file directory of target files')
file_list = os.listdir()

# create dictionary containing all sample ID
ID_data = open('ID_list_csv_file.csv', 'r')
ID_list = csv.reader(ID_data, delimiter=',')
ID_dict = {}
next(ID_list)
for line in ID_list:
    ID_dict[line[1] + ',' + line[0]] = line[2]
ID_data.close()

# change name
for fname in file_list:
    try:
        if fname[12] == ',':  # change name with 1-9
            os.rename(fname, ID_dict[fname[11:14]] + '-' + fname)
        else:  # change name with 11-19
            os.rename(fname, ID_dict[fname[11:15]] + '-' + fname)
    except Exception:
        pass

These small codings are very efficient to change large amount of filename. You can modified the codes to fit your requirements.