Skip to content

Instantly share code, notes, and snippets.

@AdamDimech
Last active May 22, 2023 15:32
Show Gist options
  • Save AdamDimech/47eed35850541e6a6c2e0c86a327f807 to your computer and use it in GitHub Desktop.
Save AdamDimech/47eed35850541e6a6c2e0c86a327f807 to your computer and use it in GitHub Desktop.
Batch rename files from a CSV via Python. Details: https://code.adonline.id.au/batch-rename-files-using-a-csv-in-python/
#!/usr/bin/env python
import os
import csv
import glob
import sys
import argparse
from datetime import datetime
from csv import reader
# Intro Text
print("\033[1;34;40m\n\nRename files from a CSV \033[0m")
print("\033[1;36;40mWritten by Adam M. Dimech\n \n \n \033[0m")
def options():
parser = argparse.ArgumentParser(description="Create a list of images from a folder in a CSV file")
parser.add_argument("-f", "--folder", help="Target folder of images.", required=True)
args = parser.parse_args()
return args
def main():
# Get options
args = options()
# Identify the target directory
target_raw = args.folder # r required to prevent reformatting numbers in path
if sys.platform.startswith('win'):
target_raw = target_raw.replace('\\', '/')
if not target_raw.endswith('/'):
target = target_raw+"/"
else:
target = os.path.join(target_raw, '')
else:
target = os.path.join(target_raw, '') # Add trailing slash if missing
# Check if renaming file exists
number_renames = len(glob.glob(target + '*renam*.csv'))
if number_renames == 0:
print("There is no 'renaming' CSV file in directory ", target, ". Please create one to continue.\n")
raise SystemExit
if number_renames >1:
print("Oops! There are", number_renames, "'renaming' CSV files in", target, ". Ensure there is only one 'renaming' file in directory.\n")
raise SystemExit
elif number_renames ==1:
csv_file = glob.glob(target + '*renam*.csv')
csv_file = csv_file [-1] # Convert from list to variable
if sys.platform.startswith('win'):
if csv_file.endswith('/'):
csv_file_rename = csv_file[:-1]
csv_file_rename = csv_file.replace('\\', '/')
print("Your renaming CSV file is located at: "+csv_file_rename+"\nPreparing to rename images...")
# Rename the CSV - Open file in read mode
with open(csv_file_rename, 'r') as read_obj:
csv_reader = reader(read_obj) # pass the file object to reader() to get the reader object
index = 0
for row in csv_reader: # Iterate over each row in the csv using reader object
index += 1 #Apply index to return row number in CSV
now = datetime.now()
if not row[1] == '': # Check that there's a proposed rename
if not index == 1: # Check that a header row isn't being used for conversions.
src = row[0]
dst = row[1]
if os.path.dirname(dst) == '': # Check that a full path is offered and if not, add one.
filename, file_extension = os.path.splitext(src) # Get src file extension
folderpath = os.path.dirname(src) # Add folder path if not specified
dst = os.path.splitext(dst)[0] # Remove file extension if present
dst = folderpath+"/"+dst+file_extension
if not os.path.isfile(src) is True: # Check that the source file can be found.
print("\033[1;31;40mWarning:\033[0m Cannot locate "+src+" (Row:"+str(index)+").")
elif os.path.isfile(dst) is True: # Check that the renamed file doesn't already exist.
print("\033[1;31;40mWarning:\033[0m File "+src+" has already been created.")
else: # Rename the file
os.rename(src, dst)
dst_short = os.path.basename(dst)
print("\033[1;32;40mSuccess!\033[0m File "+src+" (Row:"+str(index)+") was successfully renamed '"+dst_short+"' at "+now.strftime("%d-%m-%Y %H:%M:%S:%f"))
else:
print("\033[1;36;40mWarning:\033[0m File "+row[0]+" (Row:"+str(index)+") does not have a rename specified in the CSV file.")
print("Job complete.")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment