Python/DOS scripts to copy, sort and rename files.
This script clears the folder, sorts all files from the
folder, and copies them into with sequential names like , , etc.
Python Script
• The Python script scans the
sub‑folder named "images".
• It collects all files ending with
".jpg", sorts them alphabetically by filename, and then processes them one by
one.
• Before copying, it deletes the
existing "new_images" folder (if present) to ensure no old files remain.
• It creates a fresh "new_images"
folder.
• Each ".jpg" file is copied into this
new folder and renamed sequentially as "image_001.jpg", "image_002.jpg", ….
• The numbering uses three digits with
leading zeros for consistency.
rename.py
import os
import shutil
src_folder = "images"
dst_folder = "new_images"
cwd = os.getcwd()
print("Current Working Directory:", cwd)
# If the target folder exists, clear it first.
if os.path.exists(dst_folder):
shutil.rmtree(dst_folder)
# make the target folder
os.makedirs(dst_folder, exist_ok=True)
# Get all JPG files and sort them.
files = sorted([f for f in os.listdir(src_folder) if f.lower().endswith(".jpeg")])
# Copy and rename
for idx, filename in enumerate(files, start=1):
new_name = f"image_{idx:03d}.jpg" # image_001.jpg format
src_path = os.path.join(src_folder, filename)
dst_path = os.path.join(dst_folder, new_name)
shutil.copy2(src_path, dst_path)
print("Done! new_images has been cleared and all files have been regenerated.")
Windows DOS Batch Script
• The batch script performs the same
task but directly in Windows Command Prompt.
• It checks if the "new_images" folder
exists; if so, it removes the entire folder and its contents.
• It then recreates the folder.
• Using the "dir" command, it lists
all ".jpg" files in the "images" folder, sorted alphabetically.
• Each file is copied into
"new_images" and renamed sequentially as "image_001.jpg", "image_002.jpg", …
with three‑digit numbering.
rename.bat
@echo off
setlocal enabledelayedexpansion
set SRC=images
set DST=new_images
:: If the target folder exists, delete the entire folder.
if exist "%DST%" rd /s /q "%DST%"
:: make the target folder
mkdir "%DST%"
set /a count=1
for /f "tokens=*" %%f in ('dir /b /on "%SRC%\*.jpg"') do (
set "num=000!count!"
set "num=!num:~-3!"
copy "%SRC%\%%f" "%DST%\image_!num!.jpg"
set /a count+=1
)
echo Done! new_images has been cleared and all files have been regenerated.

Comments
Post a Comment