python 定时备份和删除某时间段前的文件


import sys
import os
import time
import datetime
import shutil

fileFolder = r'D:\BPM'

fileNamedir = r'D:\BackupBPM'  # 修改成存放备份的目录并在服务器上建立好。

filebak_log = r"D:\BackupBPM\filebak.log"


def delFiles(func):
    def delOldFiles(*args, **kwargs):
        ds = list(os.walk(fileNamedir))  # 获得所有文件夹的信息列表
        delta = datetime.timedelta(days=60)  # 设定60天前的文件为过期
        now = datetime.datetime.now()  # 获取当前时间

        for d in ds:  # 遍历该列表
            os.chdir(d[0])  # 进入本级路径,防止找不到文件而报错
            if d[2] != []:  # 如果该路径下有文件
                for x in d[2]:  # 遍历这些文件
                    if x != 'filebak.log':

                        ctime = datetime.datetime.fromtimestamp(os.path.getctime(x))  # 获取文件创建时间
                        print("删除过期文件", x, ctime)
                        if ctime < (now - delta):  # 若创建于delta天前
                            os.remove(x)  # 则删掉s
        func(*args, **kwargs)

    return delOldFiles


@delFiles
def work():
    fileName = fileNamedir + r'\BPM_bak_' + time.strftime('%Y%m%d%H')
    print('----开始备份----')

    shutil.make_archive(fileName, 'zip', root_dir=fileFolder)

    print('----备份完成----' + time.strftime('%Y%m%d%H'))
    with open(filebak_log, 'a') as filebak:
        filebak.write('successfull backup to %s \n' % fileName)


def main(hour, minute):
    print('工具启动')
    while True:
        while True:
            now = datetime.datetime.now()
            if now.hour == hour and now.minute == minute:
                break
        work()
        time.sleep(180)


if __name__ == '__main__':
    main(15, 25)
    # print(list(os.walk(fileNamedir)))

猜你喜欢

转载自www.cnblogs.com/python99/p/12957430.html