Python世界:文件自动化备份实践

ops/2024/9/24 6:21:22/

Python世界:文件自动化备份实践

    • 背景任务
    • 实现思路
    • 坑点小结

背景任务


问题来自《简明Python教程》中的解决问题一章,提出实现:对指定目录做定期自动化备份。

最重要的改进方向是不使用 os.system 方法来创建归档文件, 而是使用 zipfile 或 tarfile 内置的模块来创建它们的归档文件。 ——《简明Python教程》

本文在其第4版示范代码基础上,尝试采用内部python自带库zipfile的方式,实现功能:进行文件压缩备份。

实现思路


文件命名demo_backup_v5.py,视为改进的第5版实现,除采用自带zipfile的方式,还有以下更新:

  • 支持外部自定义设参
  • 支持自定义压缩文件内目录名称,并去除冗余绝对路径

编码思路:

  1. 指定待备份目录和目标备份路径
  2. 按日期建立文件夹
  3. 按时间建立压缩文件

首先,进行输入前处理,对目录路径进行处理:

python">    if len(sys.argv) >= 3: # 有外部入参,取外部输入tobe_backup_dir = sys.argv[1] # input dir, sys.argv[0] the name of python filetarget_dir = sys.argv[2] # output dircomment_info = input("enter a comment information => ")else: # 无外部入参,则内部设定# tobe_backup_dir = "C:\\Users\\other"tobe_backup_dir = r"E:\roma_data\code_data_in\inbox"target_dir = "E:\\roma_data\\code_test"comment_info = "test demo"

其次,正式进入程序处理函数:backup_proc(),先判断目标备份目录是否存在,如不存在,先构造1个。

接着,按日期today进行备份文件夹创建,按时间now进行压缩文件命名备份。

最后,遍历待备份源目录所有文件,将其压缩为时间now命名的zip文件中。

python"># 仅支持单个目录备份
def backup_proc(tobe_backup_dir, target_dir, comment_info):if_not_exist_then_mkdir(target_dir)today = target_dir + os.sep + "backup_" + time.strftime("%Y%m%d") # 年、月、日now = time.strftime("%H%M%S") # 小时、分钟、秒print("Successfully created")# zip命名及目录处理prefix = today + os.sep + nowif len(comment_info) == 0:target = prefix + '.zip'else:target = prefix + "_" + comment_info.replace(" ", "_") + '.zip'if_not_exist_then_mkdir(today)# 参考链接:https://blog.csdn.net/csrh131/article/details/107895772# zipfile打开文件句柄, with打开不用手动关闭with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as f:for root_dir, dir_list, file_list in os.walk(tobe_backup_dir): # 能遍历子目录所有文件for name in file_list:target_file = os.path.join(root_dir, name)all_file_direct_zip = Falseif all_file_direct_zip: # 不加内部目录zip_internal_dir_prefix = os.sepelse: # 加内部目录zip_internal_dir_prefix = comment_info + os.sep# 去掉绝对路径指定压缩包里面的文件所在目录结构   arcname = zip_internal_dir_prefix + target_file.replace(tobe_backup_dir, "")# arcname = target_file.replace(tobe_backup_dir, "")f.write(target_file, arcname=arcname)return

测试用例

  • python外部入参
    • python demo_backup_v5.py “E:\roma_data\code_data_in\inbox” “E:\roma_data\code_test”
  • python内部入参

本实现的一个缺点是,仅支持单一目录备份,秉持短小精悍原则,如需多目录备份可在以上做加法。

坑点小结


坑点1:不要多级目录,去除绝对路径

解决:zipfile压缩包如何避免绝对路径

坑点2:Unable to find python module

运行if not os.path.exists(path_in)报错。

根因:python有多个版本,3.6运行时不支持,需要>=3.8。

解决:Ctrl + Shift + P,输入Select Interpreter,指定高版本版本解释器。

参考:link1,link2

坑点3:TypeError: stat: path should be string, bytes, os.PathLike or integer, not list

根因:输入的path路径是个list没有拆解开,索引访问元素给string输入。

示例实现:

python"># -*- coding: utf-8 -*-
"""
Created on 09/03/24
功能:文件备份
1、指定待备份目录和目标备份路径
2、按日期建立文件夹
3、按时间建立压缩文件
"""import os
import time
import sys
import zipfile# 判断该目录是否存在,如不存在,则创建
def if_not_exist_then_mkdir(path_in):if not os.path.exists(path_in):os.mkdir(path_in)print("Successfully created directory", path_in)# 仅支持单个目录备份
def backup_proc(tobe_backup_dir, target_dir, comment_info):if_not_exist_then_mkdir(target_dir)today = target_dir + os.sep + "backup_" + time.strftime("%Y%m%d") # 年、月、日now = time.strftime("%H%M%S") # 小时、分钟、秒print("Successfully created")# zip命名及目录处理prefix = today + os.sep + nowif len(comment_info) == 0:target = prefix + '.zip'else:target = prefix + "_" + comment_info.replace(" ", "_") + '.zip'if_not_exist_then_mkdir(today)# 参考链接:https://blog.csdn.net/csrh131/article/details/107895772# zipfile打开文件句柄, with打开不用手动关闭with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as f:for root_dir, dir_list, file_list in os.walk(tobe_backup_dir): # 能遍历子目录所有文件for name in file_list:target_file = os.path.join(root_dir, name)all_file_direct_zip = Falseif all_file_direct_zip: # 不加内部目录zip_internal_dir_prefix = os.sepelse: # 加内部目录zip_internal_dir_prefix = comment_info + os.sep# 去掉绝对路径指定压缩包里面的文件所在目录结构   arcname = zip_internal_dir_prefix + target_file.replace(tobe_backup_dir, "")# arcname = target_file.replace(tobe_backup_dir, "")f.write(target_file, arcname=arcname)returnif __name__ == '__main__':print('start!')# 前处理if len(sys.argv) >= 3: # 有外部入参,取外部输入tobe_backup_dir = sys.argv[1] # input dir, sys.argv[0] the name of python filetarget_dir = sys.argv[2] # output dircomment_info = input("enter a comment information => ")else: # 无外部入参,则内部设定# tobe_backup_dir = "C:\\Users\\other"tobe_backup_dir = r"E:\roma_data\code_data_in\inbox"target_dir = "E:\\roma_data\\code_test"comment_info = "test demo"# 正式运行backup_proc(tobe_backup_dir, target_dir, comment_info)# 正式退出main函数进程,以免main函数空跑print('done!')sys.exit()

http://www.ppmy.cn/ops/107768.html

相关文章

如何在 Ubuntu 24.04 上安装 MariaDB ?

MariaDB 是一个流行的开源关系数据库管理系统,它是 MySQL 的一个分支,它被广泛用于存储和管理数据。本指南将引导您完成在 Ubuntu 24.04 上安装 MariaDB 的步骤。 Step 1: Update Your System 首先更新系统,确保所有的软件都是最新的。 su…

单片机毕业设计-基于单片机的运动手环

文章目录 前言资料获取设计介绍功能介绍程序代码部分参考 设计清单具体实现截图参考文献设计获取 前言 💗博主介绍:✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师,一名热衷于单片机技术探索与分享的博主、专注于 精通51/STM32/MSP…

调研-libevent

基础概念 官网: libevent API提供一种机制,可以在以下情况下执行回调 fd上出现具体事件、超时时间到达后、支持信号、定期超时产生的回调。libevent 旨在取代 事件驱动的网络服务器中的事件循环,程序只需要调用event_dispatch,然后动态添加或删除事件,无需更改事件循环。 …

探索全光网技术 | 全光网产品解决方案整理-(宇洪科技)

探索全光网技术 |全光网产品解决方案整理-宇洪科技 目录 一、数据中心场景1、方案概述2、方案需求3、相关产品4、产品推荐5、方案价值 二、教育场景1、方案概述2、方案需求3、相关产品4、方案价值 三、医疗场景1、方案概述2、方案需求3、相关产品4、方案价值 注:本文…

每日一练:合并区间

一、题目要求 以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 示例 1: 输入:in…

Windows环境下VS2022编译 Speex 源码

Speex Speex 是一个开源的语音压缩格式,专为语音数据设计,提供了高压缩率的同时保持较低的比特率,适合网络传输。它采用了先进的编码算法,能够在保证声音质量的同时,大幅度降低文件大小,特别适用于实时通信…

2.2.3 UDP的可靠传输协议QUIC 2

udp可靠传输 kcp协议 网络通畅下,kcp比tcp慢 这里直接看课件图片, 延迟ack比非延迟减少应答包数量,但是慢 kcp 讲解 kan代码ikcp.c 按照readme指南编译一下!! mkdir build cd build cmake .. make第一遍报错&#xf…

Pinterest账号被封?试试这几种解封方法

Pinterest作为一个充满创意与灵感的视觉社交平台,吸引着大量用户和企业前来展示、收藏和分享他们的作品。然而,如同其他社交媒体平台一样,Pinterest也设立了一套严格的使用规则和监测机制,以保障平台内容的质量和用户的良好体验。…