需求:公司需要把日志进行打包以及压缩,日志分为两种格式
第一种:2019-10-12.log (属于文件,需要每天进行压缩)
第二种:2019-10 (属于文件夹,只需要把上个月的文件夹进行压缩)
这里将两种整合到一个脚本里,让其每天执行。如果遇到第二种情况,就判断有没有属于上个月的文件夹,如果有,就将其压缩打包,如果没有,就跳过
import os import zipfile import datetime,time from dateutil.relativedelta import relativedelta ######################################################################### # File Name: log_zip.py # Created on: 2019-11-25 16:30:46 # Author: xieys # Last Modified: 2019-11-25 16:30:46 # Description: # 需求:需要把日志文件进行打包,这里有两种格式 #第一种格式:2019-11-24.log (属于文件) #第二种格式:2019-10 (属于文件夹) ######################################################################### tanyu_writeLog = r'D:IIS_htmlKMMicro_Food_TanyuWriteLog' wcf_tanyu = r'D:IIS_htmlKMMicro_WCF_TanyuLogINFO2019' infomation_tanyu_nlog = r'D:IIS_htmlKMMicro_Infomation_TanyuLogsNLogDebug' infomation_tanyu_debug = r'D:IIS_htmlKMMicro_Infomation_TanyuLogsDEBUG2019' def tar_log(path,strfdate): if strfdate == '%Y-%m-%d': log_file = '%s.log'% ((datetime.date.today() + datetime.timedelta(days = -1)).strftime(strfdate)) base_file = os.path.join(path, log_file) if os.path.exists(base_file): zip_file = zipfile.ZipFile('%s.zip'%base_file,'w', zipfile.ZIP_STORED, True) os.chdir(path) zip_file.write(log_file, compress_type=zipfile.ZIP_LZMA) zip_file.close() os.remove(base_file) else: dir_name = os.path.join(path,(datetime.date.today() - relativedelta(months=+1)).strftime(strfdate)) if os.path.exists(dir_name) and os.path.isdir(dir_name): zip_file = zipfile.ZipFile('%s.zip' % dir_name,'w', zipfile.ZIP_STORED, True) os.chdir(path) file_ls = tar_dir(dir_name,[]) for i in file_ls: log_file = i.replace(path+'\','') zip_file.write(log_file, compress_type=zipfile.ZIP_LZMA) if os.path.isdir(i): continue else: os.remove(i) zip_file.close() emp_dir = reversed(tar_dir(dir_name,[])) for i in emp_dir: try: os.removedirs(i) except Exception as e: pass else: pass def tar_dir(path,file_list): ''' 递归获取所有文件以及文件夹路径,然后返回 :param path: :param file_list: :return: ''' for i in os.listdir(path): files = os.path.join(path,i) if os.path.isdir(files): file_list.append(files) tar_dir(files,file_list) else: file_list.append(files) # file_list.append(os.path.join(os.path.basename(path),i)) return file_list if __name__ == '__main__': tar_log(tanyu_writeLog,'%Y-%m-%d') tar_log(wcf_tanyu,'%Y-%m') tar_log(infomation_tanyu_nlog,'%Y-%m-%d') tar_log(infomation_tanyu_debug ,'%Y-%m')