Published: February 4, 2018
by Tobias Pleyer
Tags: python

Renaming annoying generic picture names

A really quick and dirty script to rename pictures with a generic filename to have more meaningful names. One especially annoying thing is when the pictures have the camera’s picture count in them, e.g. CAM_2345.jpg.

The script will search for pictures meeting a glob pattern, e.g. CAM_*, and rename all of these files given the new basename and a meaningful counter, starting at 1 and padded with zeros, i.e. “001” instead of just 1.

The script isn’t very user friendly or error proof etc., but it does the job, uses Python’s new pathlib library and was hacked in under 10 minutes.

import sys
from pathlib import Path


folder = sys.argv[1]
pattern = sys.argv[2]
name_pattern = sys.argv[3]

folderpath = Path(folder)
filepaths = list(folderpath.glob(pattern))

pic_counter = 1
name_format = name_pattern + "{:03}{}"

for filepath in filepaths:
    if filepath.is_file():
        new_name = name_format.format(pic_counter, filepath.suffix)
        filepath.rename(folderpath/new_name)
        pic_counter += 1
# Example usage
$ python3 path/to/picture/folder 'CAM_*' 'my_better_name'