开发者

rename files with python - regex

开发者 https://www.devze.com 2023-01-21 19:18 出处:网络
I am wanting to rename 1k files using开发者_如何学Go python. they are all in the format somejunkDATE.doc

I am wanting to rename 1k files using开发者_如何学Go 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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消