Requirements: Companies need to package and compress the log, the log is divided into two formats
The first: 2019-10-12.log (belonging to the file, you need to compress a day)
The second: 2019-10 (belonging to the folder, just put last month's folder is compressed)
Both here integrated into a script, let execute every day. If you encounter the second case, it is judged that there is no part of last month's folder, if there is, it will be compressed package, if not, skip
Import os Import the ZipFile Import datetime, Time from dateutil.relativedelta Import relativedelta # ################################### ##################################### # File the Name: log_zip.py # the Created ON: 2019- 16:30:46 11-25 # Author: xieys # Last Modified: 2019-11-25 16:30:46 # the Description: # demand: the need to package the log files, there are two formats # the first format: 2019-11-24.log (belonging to the file) # The second format: 2019-10 (belonging to the folder) # ######################## ################################################ tanyu_writeLog = r'D:\IIS_html\KMMicro_Food_Tanyu\WriteLog' wcf_tanyu = r'D:\IIS_html\KMMicro_WCF_Tanyu\Log\INFO\2019' infomation_tanyu_nlog = r'D:\IIS_html\KMMicro_Infomation_Tanyu\Logs\NLog\Debug' infomation_tanyu_debug = r'D:\IIS_html\KMMicro_Infomation_Tanyu\Logs\DEBUG\2019' 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 the else : The os.remove (I) zip_file.close () emp_dir = the reversed (tar_dir (dir_name, [])) for I in emp_dir: the try : os.removedirs (I) the except AS E Exception: Pass the else : Pass DEF tar_dir (path, file_list): '' ' recursively obtain all files and folder path, and then return : 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 ' )