'Renaming a single directory of files with a specific syntax

I'm trying to rename and add pad the names of a few hundred files to the same length.

So far I've managed to correctly rename and pad the file names within my IDE but I'm not sure how I link that to actually rename the files themselves.

Atomic Samurai__________.png
BabyYodatheBased________.png
Baradum_________________.png
bcav____________________.png

This is the code that does the rename and the padding within my IDE:

import glob, os

pad_images = glob.glob(r"C:\Users\test\*.png")

split_images = []
for i in pad_images:
    split = i.split("\\")[-1]
    split_images.append(split)

longest_file_name = max(split_images, key=len) 
longest_int = len(longest_file_name)

new_images = []
for i in split_images:
    parts = i.split('.')
    new_name = (parts[0]).ljust(longest_int, '_') + "." + parts[1])

I've been trying to get os.rename(old_name, new_name) to work but I'm not sure where I actually get the old name from as I've split things up into different for loops.



Solution 1:[1]

Try saving the old file names to a list and do all the modifications (split and rename) in a single loop thereafter:

path = "C:/Users/test"
images = [f for f in os.listdir(path) if f.endswith(".png")]
length = len(max(images, key=len))

for file in images:
    parts = file.split("\\")[-1].split(".")
    new_name = f'{parts[0].ljust(length,"_")}.{parts[1]}'
    os.rename(os.path.join(path,file), os.path.join(path,new_name))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1