这个脚本还有待完善,没有加入迭代子目录,后期完善。
#!/bin/env python
#coding=utf-8
import time,datetime,os,sys
dir='/usr/local/src'
#被删除文件写入日志文件
logdir='/var/log'
logfile=os.path.join(logdir,'delete.log')
# 定义时间格式
time_format = "%a %b %d %H:%M:%S %Y"
# 函数返回"2015-02-28 14:50:12"格式时间
def string2time(str_time):
f_time=datetime.datetime.strptime(str_time,time_format)
f_time=f_time.strftime('%Y-%m-%d %H:%M:%S')
return f_time
#取得当前时间
today=datetime.datetime.now()
#定义2个星期
four_weeks=datetime.timedelta(weeks=2)
#取得2星期前日期
four_weeks_ago=today - four_weeks
#将时间转成timestamps
four_weeks_ago_timestamps=time.mktime(four_weeks_ago.timetuple())
#列出目录中所有文件
files=os.listdir(dir)
#打开要删除的文件日志
fh=open(logfile,"w+")
for i in files:
#忽略.开头文件
if i.startswith('.'):
continue
#忽略目录
if os.path.isdir(os.path.join(dir,i)):
continue
#获取文件的modify时间,并转化成timestamp格式
file_timestamp=os.path.getmtime(os.path.join(dir,i))
file_time_f=string2time(time.ctime(file_timestamp))
#比较文件modify时间和2周前时间,取出小于等于2周前日期的文件
if float(file_timestamp) <= float(four_weeks_ago_timestamps):
print os.path.join(dir,i)
#os.remove(os.path.join(dir,i))
fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,i) + "\n")
fh.close()
转载于:https://blog.51cto.com/yayang/1616361