开发者

How to append a file's creation date to its filename?

I would like to create a python script that appends the file created date to the end of the filename whi开发者_Python百科le retaining the oringinal file name (Report) for a batch of pdf documents.

directory = T:\WISAARD_Web Portal Projects\PortalLogging\WebLogExpert
filenames = Report.pdf


import os,time
root="/home"
path=os.path.join(root,"dir1")
os.chdir(path)
for files in os.listdir("."):
    if files.endswith(".pdf"):
        f,ext = os.path.splitext(files)        
        d=time.ctime(os.path.getmtime(files)).split() #here is just example. you can use strftime, strptime etc to format your date as desired
        filedate = d[-1]+"-"+d[-2]+"-"+d[-3]
        newname = f+filedate+ext
        try: 
            os.rename(files,newname)
        except Exception,e:
            print e
        else:
            print "ok: renamed %s to %s " %(files,newname)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜