Python找出3天前的备份压缩后删除

脚本会自动遍历目录找出时间戳距今超过3天的文件压缩,然后删除源文件。

import os
from datetime import datetime
import zipfile

#压缩文件
def create_zip(file, output_filename):
    with zipfile.ZipFile(output_filename, 'w') as zipf:
         zipf.write(file)
#找出日期小于当前日期三天的文件压缩并删除
def dbtar(directory, suffix):
    files = []
    for root, dirs, filenames in os.walk(directory):
        for filename in filenames:
            if filename.endswith(suffix):
                files.append(os.path.join(root, filename))
    for file in files:
        times = abs(datetime.now()-datetime.fromtimestamp(os.path.getmtime(file))).days
        if times > 2:
            create_zip(file,file+".zip")
            os.remove(file)
    print ("操作完成!")

dbtar('/opt/backup/db','.dmp')

推荐python3执行该脚本。

本文为原创文章,转载请注明出处。

原文链接:https://850406.xyz/post/python找出3天前的备份压缩后删除

评论(0)

还没有评论,来抢沙发吧~

验证码