Home > Enterprise >  Trying to replace image extensions like "<filename>.<extension>" to "<
Trying to replace image extensions like "<filename>.<extension>" to "<

Time:11-06

I'm trying to use this code in Python using regular expression to get all the image files (of types jpg, png and bmp) in my current folder and add a word "resized" inbetween the filename and the extension

Input

  • Batman - The Grey Ghost.png
  • Mom and Dad - Young.jpg

Expected Output

  • Batman - The Grey Ghost_resized.png
  • Mom and Dad - Young_resized.jpg

Query

But my output is not as expected. Somehow the 2nd letter of the extension is getting replaced. I have tried tutorials online, but didn't see one which answers my query. Any help would be appreciated.

Code:

import glob
import re
files=glob.glob('*.[jp][pn]g') glob.glob('*.bmp')

for x in files:
    new_file = re.sub(r'([a-z|0-9]).([jpb|pnm|ggp])$',r'\1_resized.\2',x)
    print(new_file,' : ',x)

Code Output

Ma image scan - Copy.j\_resized.g  :  Ma image scan - Copy.jpg
Ma image scan.j\_resized.g  :  Ma image scan.jpg
Mom and Dad - Young.j\_resized.g  :  Mom and Dad - Young.jpg
PPF - SBI - 4.j\_resized.g  :  PPF - SBI - 4.jpg
when-youre-a-noob-programmer-and-you-think-your-loop-64102565.p\_resized.g  :  when-youre-a-noob-programmer-and-you-think-your-loop-64102565.png
Sample.b\_resized.p  :  Sample.bmp


CodePudding user response:

Try this:

r'([a-zA-Z0-9_ -] )\.(bmp|jpg|png)$'

Input:

  • Batman - The Grey Ghost.png

Output:

  • Batman - The Grey Ghost_resized.png

See live demo.

  • Related