Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading