Nanfeng

Notes on software development, code, and curious ideas

Batch-Renaming Images with a Python Prefix Script

I recently needed to rename a large number of images. Doing it one file at a time was tedious, so I wrote a small batch-processing script.

What the script does

The script finds .jpg and .png files in a source directory, adds a user-supplied prefix to each filename, and copies the renamed files to a destination directory. The originals remain unchanged.

Environment

Python 3 or later.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
import shutil

src_folder = input("Enter the folder containing the images: ")
dest_folder = input("Enter the destination folder: ")
prefix = input("Enter the filename prefix: ")

if not os.path.exists(src_folder):
print("The specified source folder does not exist")
else:
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)

files = os.listdir(src_folder)

for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
new_name = prefix + file
old_path = os.path.join(src_folder, file)
new_path = os.path.join(dest_folder, new_name)
shutil.copy2(old_path, new_path)
print(f'Copied and renamed: {file} to {new_name}')

On systems with case-sensitive suffix checks, extend the condition or use file.lower().endswith(('.jpg', '.png')) if files may use uppercase extensions.

+