I have this python script which will take these three arguments:
- a given path for a directory with files to rename
- a CSV file with two columns to map the file names to:
original,new
barcode01,sample01
barcode02,sample02
- extension of the file (i.e. .txt, .bam, .png, .txt.readdb.log) which can be long.
The script:
import os
import csv
def rename_files(path, name_map, ext):
with open(name_map, 'r') as csv_map:
filereader = csv.DictReader(csv_map)
for row in filereader:
original_name = row["original"]
new_name = row["new"]
old_filename = '%s/%s.%s' % (path, original_name, ext)
new_filename = '%s/%s_%s.%s' % (path, new_name, original_name, ext)
try:
os.rename(old_filename, new_filename)
except Exception as e:
print('Rename for file %s failed. Details: ' % old_filename)
print (e)
if __name__ == '__main__':
filename, path, name_map, ext = sys.argv
rename_files(path, name_map, ext)
For example:
python rename.py /test/directory filestorename.csv txt
will only rename barcode01.txt to sample01.txt.
However, there are multiple barcode01 files with different extensions (i.e. barcode01.png). Instead of passing these extensions as arguments to the script, how can I modify this script to just rename all these files at once, keeping the extension the same?