例子,python基础教程实例,删除指定日期前的指定文件,用到了os、datetime等模块。
代码:
#-*- coding:gbk-*-
#jb200.com
#version 1.01
import getopt,sys,string
import os, datetime,time,glob
from stat import *
reload(sys)
sys.setdefaultencoding('utf-8')
IFS="/" #路径分割符
_delday = "7"
_deldir = "/tmp"
_delext = "log"
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=log] : only delete filename extension like .log files"
print " : support * , will delete all files"
print " [-d /tmp|--dir=/tmp] : only delete /tmp dirctory's files"
print " Default parameter is delete /tmp all .rar files before 7 day"
print " Ex:"
print " dnd.exe -y 7 -d /usr/local/apache/logs/ -e log"
print " or"
print " dnd.exe --day=7 --dir=/usr/local/apache/logs/ --ext=log"
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__'