#-*- coding:gbk-*- #code by HAWK.Li #version 1.0 #2009-02-06 import getopt,sys,string import os, datetime,time,glob from stat import * reload(sys)
sys.setdefaultencoding('utf-8') IFS="\\" #路径分割符,linux用"/" win32用"\\"
_delday = "7" _deldir = "d:\\temp\\" _delrar = "rar" def getargv(): if len(sys.argv) <2: usage() sys.exit(3) try: opts, args = getopt.getopt(sys.argv[1:], "hy:d:e:", ["help", "day=", "dir=", "rar="]) except getopt.GetoptError: usage() sys.exit(2) for o, a in opts: if o in ("-y", "--day"): global _delday _delday = a elif o in ("-d", "--dir"): global _deldir _deldir = a elif o in ("-e", "--rar"): global _delrar _delrar = a else: usage() sys.exit() def usage(): print "this program will delete specified files at created by N days." print u"本程序用于删除指定目录下文件修改日期在指定时间前的指定后缀类型文件" print " usage:" print " -h, --help : this help screen" print " [-y 7|--day=7] : delete files before 7 day" print " [-e rar|--ext=rar] : only delete filename extension like .rar files" print " : support * , will delete all files" print " [-d d:\\tmp|--dir=d:\\tmp] : only delete d:\\tmp dirctory's files" print " Default parameter is delete d:\\temp all .rar files before 7 day" print " Ex:" print " dnd.exe -y 7 -d d:\\test\\ -e rar" print " or" print " dnd.exe --day=7 --dir=d:\\test\\ --ext=rar"
def erasefile(Eday,Edir,Erar): print "Erase files program starting..." logpath=Edir count=False fullpath=glob.glob(Edir+'\*.'+Erar) for i in range(len(fullpath)): t1 = time.gmtime(os.stat(fullpath[i])[ST_MTIME]) #get file's mofidy time t11 = time.strftime('%Y-%m-%d',t1) year,month,day=t11.split('-') t111= datetime.datetime(int(year),int(month),int(day)) t2 = time.gmtime() t22 = time.strftime('%Y-%m-%d',t2) year,month,day=t22.split('-') t222= datetime.datetime(int(year),int(month),int(day)) days = (t222-t111).days if days>string.atof(Eday): # if over N days then remove file try: os.remove(fullpath[i]) print fullpath[i] ,"deleted." count = True log=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+" remove "+fullpath[i]+" success \n" except: log=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+" remove "+fullpath[i]+" fail \n" fTemp=open(logpath+IFS+"remove_file.log", 'a') fTemp.write(log) if count == False: print "No file be deleted." print "Erase files program End..."
if __name__ == '__main__
|