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

2024-09-04 00:44

本文主要是介绍Python世界:文件自动化备份实践,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

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

背景任务


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

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

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

实现思路


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

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

编码思路:

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

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

    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文件中。

# 仅支持单个目录备份
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内部入参
    • python demo_backup_v5.py

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

坑点小结


坑点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输入。

示例实现:

# -*- 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()

这篇关于Python世界:文件自动化备份实践的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1134518

相关文章

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3