Image File Renaming Script

This page describes the development of a python script that can rename a sequence of image files.

 
 

ALGORITHM

1. Find the path to the parent ("images") directory.
2. Get a listing of all the .exr files.
3. For each file in the listing:
        3.1 check its name matches some criteria,
        3.2 make a duplicate of the file,
        3.3 rename the duplicate to the shortened name.
4. Print a confirmation of the action(s) taken.

 

RUNNING THE CODE

1. Copy the two scripts to the folder containing the images to be renamed.
2. On Linux double click the file called "file_rename", on Windows double click the file called "file_rename.bat".

 

THE CODE - "file_rename.py"

import os
import os.path
import shutil
import glob
import inspect
  
# 1. Find the path to the parent ("images") directory.
fullpath = inspect.getframeinfo(inspect.currentframe()).filename
dirpath = os.path.dirname(os.path.abspath(fullpath))
  
# 2. Get a listing of all the .exr files.
glob_pattern = os.path.join(dirpath, '*.exr')
paths = glob.glob(glob_pattern)
  
for path in paths:
    fname = os.path.basename(path)  
    # 3.1 check the file name matches some criteria
    if fname.startswith('first__'): 
        src_path = os.path.join(dirpath, fname)
        dup_path = os.path.join(dirpath, 'dup.exr')
  
        # 3.2 make a duplicate of the file
        shutil.copy2(src_path,dup_path)
        
        # 3.3 rename the duplicate to the shortened name     
        dest_path = os.path.join(dirpath, fname[7:])
        os.rename(dup_path, dest_path) 
        print('processed file named %s' % fname)
    else:
        print('ignoring %s' % fname)
 

SHELL SCRIPTS

Linux - "file_rename"

python file_rename.py
read

Windows - "file_rename.bat"

C:\python27\python file_rename.py
pause

 

RESTRICTIONS

This is meant as an example for the process of renaming and duplicating files. The code assumes that the files to be renamed begin with "first__" and are located in a specific directory that may differ from user to user. This code should be use as a starting point and should be tailored to suit the user's needs.