rename files with python – regex – Education Career Blog

I am wanting to rename 1k files using python. they are all in the format somejunkDATE.doc

basically, I would like to delete all the junk, and only leave the date. I am unsure how to match this for all files in a directory.



If your date format is the same throughout, just use slicing

>>> file="someJunk20101022.doc"
>>> file-12:
>>> import os
>>> os.rename(file, file-12:

If you want to check if the numbers are valid dates, pass file-12:-3 to time or datetime module to check.

Say your files are all in a directory (no sub directories)

import os
import glob
import datetime,time #as required
for files in glob.glob("*.doc"):
    newfilename = files-12:
    # here to check date if desired
    except OSError,e:
       print e
    else: print "ok"

Leave a Comment