#! /usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
import time,datetime
# 定义需要删除文件的目录
dir = '/data/webbak/'
# 被删除文件写入日志文件
logdir = '/var/log'
logfile = os.path.join(logdir, 'delete.log')
# 获取当前系统python版本
ver = sys.version
ver = ver.split(' ')
ver = ver[0]
# 将"Wed Jul 4 13:25:59 2012"格式的时间转成“2012-07-02 14:50:15”格式的时间
# version是当前系统python版本号
# time是"Wed Jul 4 13:25:59 2012"格式的时间
# 函数返回"2012-07-02 14:50:15"格式的时间
def string2time(str_time, version = ver):
version_l = version.split('.')[0:2]
ver = version_l[0] + '.' + version_l[1]
if (ver == '2.7'):
f_time = datetime.datetime.strptime(str_time, time_format)
f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
return f_time
elif(ver == '2.4'):
f_time = time.strptime(str_time, time_format)
f_time = datetime.datetime(*f_time[0:6])
return f_time
# 时间格式
time_format = "%a %b %d %H:%M:%S %Y"
# 取得当前时间
today = datetime.datetime.now()
# 定义4个星期
four_weeks = datetime.timedelta(weeks=6)
# 4星期前的日期
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 f in files:
# 忽略掉.开头的文件
if f.startswith('.'):
continue
# 忽略掉当前目录下的目录
if os.path.isdir(os.path.join(dir,f)):
continue
# 获得文件的modify时间,并转换成timestamp格式
file_timestamp = os.path.getmtime(os.path.join(dir, f))
file_time_f = string2time(time.ctime(file_timestamp))
if float(file_timestamp) <= float(four_weeks_ago_timestamps):
fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,f) + "\n")
os.remove(os.path.join(dir,f))
# 关闭文件
fh.close()
脚本2:
实现类似下面的Shell命令的操作
复制代码 代码如下:
find /data/log -ctime +5 | xargs rm -f
Python代码:
复制代码 代码如下:
import os
import sys
import time
class DeleteLog:
def __init__(self,fileName,days):
self.fileName = fileName
self.days = days
def delete(self):
if os.path.isfile (self.fileName):
fd = open(self.fileName,'r')
while 1:
バッファ = fd.readline()
バッファでない場合: OSの場合.path.isfile(buffer):
os.remove(buffer)
fd.close()
elif os.path.isdir(self.fileName):
for i in [os. 9月.join([self.fileName,v]) for v in os.listdir(self.fileName)]:
print i
if os.path.isfile(i):
if self.compare_file_time( i):
os.remove(i)
elif os.path.isdir(i):
self.fileName = i
self.delete()
def Compare_file_time(self,file ):
time_of_last_access = os.path.getatime(file)
age_in_days = (time.time()-time_of_last_access)/(60*60*24)
if age_in_days > self.days:
return True
return False
if __name__ == '__main__':
if len(sys.argv) == 2:
obj = DeleteLog(sys.argv[ 1],0)
obj.delete()
elif len(sys.argv) == 3:
obj = DeleteLog(sys.argv[1],int(sys.argv[2]) )
obj.delete()
else:
print "usage: python %s listFileName|dirName [days]" % sys.argv[0]
sys.exit(1)