How to rename images with specific pattern?

Question:

I have this image folder as shown below that has repated charchter name A I want only keep one letter A with rest of numbers + ext
the input :

input_folder --|
               |--- imgs -- |-- A_0.jpg
                            |-- A_A_A_1.jpg
                            |-- A_A_2.jpg
                            |-- A_A_A_A_3.jpg
                            |-- A_4.jpg
                            .........

I want to rename new image by keeping only Leter A+numbers+.jpg
for example if image name is A_0.jpg keep it if image name A_A_A_1.jpg rename it to A_1.jpg and so on ..

I am trying to loop throght image folder and using python or regular expression with py following this articail Rename with Regular Expression

the expacted output results in the same folder :

input_folder --|
               |--- imgs -- |-- A_0.jpg
                            |-- A_1.jpg
                            |-- A_2.jpg
                            |-- A_3.jpg
                            |-- A_4.jpg
                            .........

This issue caused by runing following script for 500 000 images rleated

Answers:

This will work for the structure and file name pattern in the question. Other naming patterns may be problematic.

from pathlib import Path
from os import rename

PATH = Path('input_folder/imgs')
SEPARATOR = '_'
REPEAT = 'A'

for file in PATH.glob('*'):
    try:
        if len(t := file.stem.split(SEPARATOR)) > 1 and t[0] == REPEAT and t[-1].isdecimal():
            newfile = t[0] + SEPARATOR + t[-1] + file.suffix
            rename(file, PATH / newfile)
    except Exception as e:
        print(e)
Answered By: DarkKnight