脚本会自动遍历目录找出时间戳距今超过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执行该脚本。