文件自动备份脚本:智能增量与多线程加速
背景与需求
在企业数据管理中,手动备份常面临文件损坏、版本覆盖或遗漏的风险。为解决这一问题,开发了一个基于 Python 的自动备份脚本,支持定时运行、智能增量检测及大文件压缩。
核心代码功能展示
该备份脚本核心逻辑在 sync_root 和 transfer_file 函数中。以下是关键部分的解析:
# 1. 智能判断:源文件是否更新过?
def size_if_newer(source, target):
src_stat = os.stat(source) # 获取源文件元数据(大小、修改时间)
try:
target_ts = os.stat(target).st_mtime
except FileNotFoundError:
target_ts = 0 # 若目标不存在返回 0
# 时间差>1 秒才认为有更新(避免亚秒级误差)
return src_stat.st_size if (src_stat.st_mtime - target_ts > 1) else False
# 2. 文件传输:自动判断压缩或直接复制
def transfer_file(source, target, compress):
try:
if compress:
# 文件大于阈值,先 gzip 压缩再存
with gzip.open(target + '.gz', 'wb') as target_fid:
with open(source, 'rb') as source_fid:
target_fid.writelines(source_fid)
print('Compress {}'.format(source))
else:
# 小文件直接复制,保留元数据
shutil.copy2(source, target)
print('Copy {}'.(source))
FileNotFoundError:
os.makedirs(os.path.dirname(target))
transfer_file(source, target, compress)
():
size = size_if_newer(source, target)
size:
thread = threading.Thread(
target=transfer_file,
args=(source, target, size > compress)
)
thread.start()
thread

