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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章