3

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

3
  • 1
    We can't help if we know nothing about how DATE is formatted. Commented Oct 21, 2010 at 0:11
  • 1
    Is the junk always the same, or is it different for each file? Also, what format is the date in? Commented Oct 21, 2010 at 0:11
  • the 'junk' also contains every type of character, symbol, etc, random lengths, rather lengthy Commented Oct 21, 2010 at 0:20

1 Answer 1

7

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.