script
#!/usr/bin/python3
# -*- coding: utf-8 -*
# 用法 要删除多个目录在最后添加哦
import os
import os.path, time, datetime
logdir1 = "/home/logs/scheduler/scheduler-web"
logdir2 = "/home/logs/market/"
#logdir = "/tmp"
def init():
if not os.path.exists(logdir):
sys.exit(0)
print("没有这个目录 exit now")
def dellog(logdir,myday):
for parent, dirnames, filenames in os.walk(logdir):
for filename in filenames:
fullname = parent + "/" + filename #文件全称
#print("%s" %fullname)
createTime = int(os.path.getctime(fullname)) #文件创建时间
# print("%s" %createTime)
#nDayAgo = (datetime.datetime.now() - datetime.timedelta(myday) #当前时间的n天前的时间
nDayAgo = (datetime.datetime.now() - datetime.timedelta(days = myday)) #当前时间的n天前的时间
timeStamp = int(time.mktime(nDayAgo.timetuple()))
#print("%s" %timeStamp)
if createTime < timeStamp: #创建时间在n天前的文件删除
#removelog=os.path.join(parent,filename)
#os.remove(removelog)
#记得在3 交互界面是报错的
print("%s" %(os.path.join(parent,filename)))
os.remove(os.path.join(parent,filename))
#print("%s" %(os.path.join(parent,filename)))
if __name__ == "__main__":
dellog(logdir=logdir1,myday=1)
dellog(logdir=logdir2,myday=2)
see also
定时清理日志文件-python实现
Python清空指定文件夹下所有文件的方法
python 删除文件、目录
python 删除文件、清空目录的方法总结
使用python删除一个文件或文件夹
python实现日志清理