views:

41

answers:

1

hello, 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.

thanks

+5  A: 

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

>>> file="someJunk20101022.doc"
>>> file[-12:]
'20101022.doc'
>>> 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
os.chdir("/mypath")
for files in glob.glob("*.doc"):
    newfilename = files[-12:]
    # here to check date if desired
    try:
       os.rename(files,newfilename)
    except OSError,e:
       print e
    else: print "ok"
ghostdog74
very cool. thanks
bernard
successful. thanks again
bernard