python--通过zipfile模块压缩文件

类似于linux执行
find ./ -name '*log' -mtime +1 -type f | xargs -i gzip {}
参考了这篇文章https://www.bbsmax.com/A/kvJ3k7v9Jg/
写的很好!

#-*-coding=utf8 -*-
import zipfile, os, time

def zip_file(file_name):
  if not os.path.isfile(file_name):
    print('file not exist! ==> %s' % file_name)
  else:
    print('file name ==> %s' % file_name)
    zip_name = file_name + '.zip'
    #z = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    z = zipfile.ZipFile(zip_name, 'w', allowZip64 = True)
    z.write(file_name)
    z.close()
    if os.path.isfile(file_name):
      os.remove(file_name)

# full path
def zip_exec(dir_name, tag, endtag, hour):
  if not os.path.exists(dir_name):
    print('dir not exist! ==> %s' % dir_name)
  else:
    print('dir name ==> %s' % dir_name)
    os.chdir(dir_name)
    for root, lists, files in os.walk('.'):
      for f in files:
        file_name = os.path.join(root, f)
        lastmodifytime = os.stat(file_name).st_mtime
        endfiletime = time.time() - 3600 * hour
        if endfiletime > lastmodifytime and tag in f and f.endswith(endtag):
          zip_file(file_name)


if __name__ == '__main__':
  zip_exec('D:\\IISlog_v5\\bflights', 'log', '.log', 24)

执行结果


v2

#-*-coding=utf8 -*-
import zipfile, os, time, shutil

def rm_files(dir_name):
  print('clean files...')
  if not os.path.exists(dir_name):
    print('dir not exist! ==> %s' % dir_name)
  else:
    print('dir name ==> %s' % dir_name)
    os.chdir(dir_name)
    for li in os.listdir('.'):
      if os.path.isfile(li):
        print('clean file ==> %s' % li)
        try:
          os.remove(li)
        except:
          print('clean file error! ==> %s' % li)
      elif os.path.isdir(li):
        print('clean dir ==> %s' % li)
        try:
          shutil.rmtree(li)
        except:
          print('clean dir error! ==> %s' % li)
    print('done!')

def clean_c():
  rm_files('C:\\ProgramData\\Microsoft\\Windows\\WER')
  rm_files('C:\\Windows\\SoftwareDistribution\\Download')
  rm_files('C:\\Users\\Administrator\\AppData\\Roaming\\GoodSync')
  rm_files('C:\\Windows\\Temp')
  rm_files('C:\\Windows\\Logs\\CBS')
  rm_files('C:\\ProgramData\\Symantec\\Symantec Endpoint Protection\\CurrentVersion\\Data\\Quarantine')
  rm_files('C:\\ProgramData\\KasperskyLab\\adminkit\\1103\\wusfiles')
  rm_files('C:\\ProgramData\\KasperskyLab\\adminkit\\bases\\Cache')

def zip_file(file_name):
  if not os.path.isfile(file_name):
    print('file not exist! ==> %s' % file_name)
  else:
    print('file name ==> %s' % file_name)
    zip_name = file_name + '.zip'
    #z = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    z = zipfile.ZipFile(zip_name, 'w', allowZip64 = True)
    z.write(file_name)
    z.close()
    if os.path.isfile(file_name):
      os.remove(file_name)
      print('%s done!' % zip_name)

# full path
def zip_exec(dir_name, tag, endtag, hour):
  print('zip files..')
  if not os.path.exists(dir_name):
    print('dir not exist! ==> %s' % dir_name)
  else:
    print('dir name ==> %s' % dir_name)
    os.chdir(dir_name)
    for root, lists, files in os.walk('.'):
      for f in files:
        file_name = os.path.join(root, f)
        lastmodifytime = os.stat(file_name).st_mtime
        endfiletime = time.time() - 3600 * hour
        if endfiletime > lastmodifytime and tag in f and f.endswith(endtag):
          zip_file(file_name)


if __name__ == '__main__':
  clean_c()
  zip_exec('D:\\IISlog_v5\\bflights', 'log', '.log', 24)

v3, 增加了压缩文件夹功能
参考文章
https://www.qedev.com/python/319381.html

import zipfile, os, time, shutil

def rm_files(dir_name):
  print('clean files...')
  if not os.path.exists(dir_name):
    print('dir not exist! ==> %s' % dir_name)
  else:
    print('dir name ==> %s' % dir_name)
    os.chdir(dir_name)
    for li in os.listdir('.'):
      if os.path.isfile(li):
        print('clean file ==> %s' % li)
        try:
          os.remove(li)
        except:
          print('clean file error! ==> %s' % li)
      elif os.path.isdir(li):
        print('clean dir ==> %s' % li)
        try:
          shutil.rmtree(li)
        except:
          print('clean dir error! ==> %s' % li)
    print('done!')

def clean_c():
  rm_files('C:\\ProgramData\\Microsoft\\Windows\\WER')
  rm_files('C:\\Windows\\SoftwareDistribution\\Download')
  rm_files('C:\\Users\\Administrator\\AppData\\Roaming\\GoodSync')
  rm_files('C:\\Windows\\Temp')
  rm_files('C:\\Windows\\Logs\\CBS')
  rm_files('C:\\ProgramData\\Symantec\\Symantec Endpoint Protection\\CurrentVersion\\Data\\Quarantine')
  rm_files('C:\\ProgramData\\KasperskyLab\\adminkit\\1103\\wusfiles')
  rm_files('C:\\ProgramData\\KasperskyLab\\adminkit\\bases\\Cache')

def zip_file(file_name):
  if not os.path.isfile(file_name):
    print('file not exist! ==> %s' % file_name)
  else:
    print('file name ==> %s' % file_name)
    zip_name = file_name + '.zip'
    #z = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    z = zipfile.ZipFile(zip_name, 'w', allowZip64 = True)
    z.write(file_name)
    z.close()
    if os.path.isfile(file_name):
      os.remove(file_name)
      print('%s done!' % zip_name)

def zip_dir(dir_name):
  if not os.path.isdir(dir_name):
    print('dir not exist! ==> %s' % dir_name)
  else:
    print('dir name ==> %s' % dir_name)
    zip_name = dir_name + '.zip'
    z = zipfile.ZipFile(zip_name, 'w', allowZip64 = True)
    zipList = []
    for dir,subdirs,files in os.walk(dir_name):
      for fileItem in files:
        zipList.append(os.path.join(dir,fileItem))
      for dirItem in subdirs:
        zipList.append(os.path.join(dir,dirItem))
    for i in zipList:
      z.write(i)
    z.close()
    if os.path.isdir(dir_name):
      shutil.rmtree(dir_name)
      print('%s done!' % zip_name)

def zip_exec(root_name, tag, tag2, hour, type):
  exit_str='pass'
  if not os.path.exists(root_name):
    #print('ROOTDIR not exist! ==> %s' % root_name)
    return exit_str
  print('root dir ==> %s' % root_name)
  os.chdir(root_name)
  if type == 'zf':
    print('zip files..')
    for root, lists, files in os.walk('.'):
      for f in files:
        file_name = os.path.join(root, f)
        lastmodifytime = os.stat(file_name).st_mtime
        endfiletime = time.time() - 3600 * hour
        if endfiletime > lastmodifytime and tag in f and f.endswith(tag2):
          zip_file(file_name)
  elif type == 'zd':
    for dir_name in os.listdir('.'):
      if os.path.isdir(dir_name):
        d = dir_name
        lastmodifytime = os.stat(d).st_mtime
        endfiletime = time.time() - 3600 * hour
        if endfiletime > lastmodifytime and tag in d and tag2 in d:
          zip_dir(d)


if __name__ == '__main__':
  clean_c()
  #bflights
  zip_exec('D:\\IISlog_v5\\bflights', 'log', '.log', 24, 'zf')
  #shareservice
  zip_exec('D:\\log4net\\ShareService', '20', '-', 24, 'zd')
  zip_exec('D:\\iislog\\shareservice\\W3SVC5', 'u_ex', '.log', 24, 'zf')

推荐阅读更多精彩内容