Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python renaming file with regex

Tags:

python

regex

Hi I want to rename files with one source pattern (for example IMG_20190401_235959.jpg) to a destination pattern (for example 2019-04-01_23_59_59.jpg)

I'm trying to do that in python but i can't find out how to use a regex to build the new filename :

#!/usr/bin/python

import os, glob, sys, re    
os.chdir(sys.argv[1])
for filename in glob.glob("IMG_*.jpg"):
    newfilename = re.sub(?????
    try:
       os.rename(filename,newfilename)
    except OSError,e:
       print e
like image 452
MaD Avatar asked Sep 01 '26 23:09

MaD


1 Answers

import re

regex = re.compile(r'^IMG_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.jpeg$')

oldStr = 'IMG_20190401_235959.jpeg';

match = regex.match(oldStr)

newStr = '{}-{}-{}_{}_{}.jpg'.format(*match.groups())

print(newStr) # 2019-04-01_23_59.jpg
like image 88
Khalid Ali Avatar answered Sep 03 '26 14:09

Khalid Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!