如何创建一个脚本,使用python将文件创建日期附加到文件名?

时间:2010-01-29 00:05:02

标签: python

我想创建一个python脚本 将文件创建日期附加到文件名末尾,同时保留一批pdf文档的oringinal文件名(“Report”)。

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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)