需求:
1、删除log目录下,所有的空文件
2、删除5天前的文件
首先构造文件夹及log文件,mkdir.py:
import os,datetime dirs = ['android','apache','app','ios','nginx','python','tomcat'] os.chdir(r'D:\workspace\python\syz-dongrui\Day6\logs')#修改当前路径 base_path = r'D:\workspace\python\syz-dongrui\Day6\logs' for d in dirs: path = os.path.join(base_path,d)#拼接子文件夹路径 os.mkdir(path)#新建文件夹 os.chdir(path)#修改当前目录至子文件夹 for i in range(10): t = datetime.date.today()-datetime.timedelta(days=i) filename = '%s-%s.log'%(d,t)#拼接文件名称 open(filename,'w')#新建文件
接着双数日期的日志,里面随便写点东西
import os for abs_path,dir,file in os.walk(r'D:\workspace\python\syz-dongrui\Day6\logs'): for f in file: day = f.split('.')[0].split('-')[-1] if int(day)%2==0: file_name = os.path.join(abs_path,f)#拼接绝对路径 open(file_name,'a+',encoding='utf-8').write('写入双数日期日志')#没有f=open()申请空间,所以不用关文件
删除过期及空文件实现:
import os,datetime,time def str2timestamp(str,format ='%Y-%m-%d' ):#格式化时间转为时间戳 tp = time.strptime(str,format) stamp = time.mktime(tp) return int(stamp) d = datetime.date.today() - datetime.timedelta(days=5)#5天前的日期 t_standard = str2timestamp(d.strftime('%Y-%m-%d'))#5天前的时间戳 for abs_path,dir,file in os.walk(r'D:\workspace\python\syz-dongrui\Day6\logs'): for f in file: if f.endswith('.log'):#仅删除文件夹下的log date = f.split('.')[0].split('-')#生成的文件格式为:android-2018-04-28.log date.pop(0) file_date = '-'.join(date)#每个文件的日期str tf = str2timestamp(file_date)#每个文件的时间戳 os.chdir(abs_path) if os.path.getsize(f) == 0 or tf < t_standard: os.remove(f)#删除所有的空文件