lkjhgd 发表于 2016-7-7 09:20:10

python备份、删除过期压缩文件

#!/usr/bin/python
#-*- coding:utf-8 -*-
import os,sys,datetime
import shutil
import time
def zipfile(s_dir,path="."):
      target = path + os.sep + s_dir.split('/')[-1] + time.strftime('%Y%m%d%H%M%S') + '.zip'
      zip_command = "zip -qr %s %s -x '*.gz'" % (target,s_dir)
      if os.system(zip_command) == 0:
                print 'Successful backup to',target
      else:
                print 'Backup Failed!'
def removeFilesBeforeDate(beforeTime, path = "."):
      for eachFile in os.listdir(path):
                f = path + os.sep + eachFile
                lastMTime = os.stat(f).st_mtime
                if lastMTime <= beforeTime:
                        try:
                              if os.path.isfile(f):
                                        os.remove(f)
                              elif os.path.isdir(f):
                                        shutil.rmtree(f)
                              else:
                                        os.remove(f)
                              print ("删除 {0}, 成功!".format(eachFile))
                        except Exception as e:
                              print("删除 {0}, 失败! 错误如下:".format(eachFile))
                              print(e)
if __name__ == '__main__':
      currTime = time.time()
      deltTime = 3600*24*7
      beforTime = currTime - deltTime
      path = "/app/sinova/back"
      s_dir = "/app/sinova/nginx_node2"
      zipfile(s_dir,path)
      removeFilesBeforeDate(beforTime, path)


页: [1]
查看完整版本: python备份、删除过期压缩文件