“Python日志删除脚本”的版本间的差异
跳到导航
跳到搜索
第44行: | 第44行: | ||
</pre> | </pre> | ||
+ | |||
+ | =see also= | ||
+ | [https://blog.csdn.net/xal0610/article/details/76154890?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1 定时清理日志文件-python实现] | ||
+ | |||
+ | [https://blog.csdn.net/Scythe666/article/details/97614113 Python清空指定文件夹下所有文件的方法] |
2020年4月28日 (二) 09:03的版本
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)