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.
Fig.1: spreadsheet with ID and locations.
Fig.2: what filenames look like before change.
Fig.3: what filenames look like after changing.
I used python os module and csv module to do this job.
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.