What you can do is to precompile the RegEx before using it. You can proceed that way:
import re
sub_name = re.compile(r"IMG_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})", flags=re.I).sub
Here, sub_name is a function that you can use later in you for loop to replace the name of each image.
Note: Ignoring the case (upper/lower-case) can be useful under Windows, but you also need to adapt the call to glob.glob.
Below is a solution which use glob.glob but you can also use os.walk to browse a directory, searching all images…
# coding: utf-8
import glob
import os
import re
import sys
sub_name = re.compile(r"IMG_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})", flags=re.I).sub
work_dir = sys.argv[1]
for old_path in glob.glob(os.path.join(work_dir, "IMG_*.jpg")):
dirname, old_name = os.path.split(old_path)
new_name = sub_name("\\1-\\2-\\3_\\4_\\5_\\6", old_name)
new_path = os.path.join(dirname, new_name)
try:
os.rename(old_path, new_path)
except OSError as exc:
print(exc)
I noticed that you use the print statement, and the Python 2.6 syntax for exception. It is preferable to use the new syntax.
If you use Python 2.7, you can add the directive:
from __future__ import print_function
Put it at the top of your imports…
.split('')the filename, add the characters you need, and rejoin.