1. 介绍

通过实例学习Python的使用,该实例来自文献[1]中的第11章解决问题。

由于没有搞清楚Win7下如何通过命令行调用zip命令,所以采用7z[2],采用7-zip命令行版本[3],版本号为7-zip 9.20,下载后需要配置环境变量,修改Path,使其包含7za.exe所在目录。

软硬件配置情况:

Win7旗舰版 SP1

Python 3.4

7-zip 9.20 命令行版本(需要配置环境变量Path)

2. 问题

写一个能给我所有重要文件建立备份的程序。

程序如何工作:

1.需要备份的文件和目录由一个列表指定。

2.备份应该保存在主备份目录中。

3.文件备份成一个zip文件。

4.zip存档的名称是当前的日期和时间。

5.使用标准的zip命令。它通常默认的随Linux/ Unix发行版提供。Windows用户可以从GnuWin32项目安装。注意你可以使用任何存档命令,只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。(本文使用了7-zip 9.20命令行版本)

解决方案来自参考文献[1]。

2.1 解决方案1

实现功能:

压缩文件备份到主目录下,文件名已目前的日期时间为名称。

代码如下所示:

 #! /usr/bin/python
# Filename: backup_ver1.py import os
import time # 1. The files and directories to be backed up are specified in a list
source = ['"D:\\QT\\py 1"','D:\\QT\\py2']
# Notice we had to use double quotes inside the string for names with spaces in it # 2. The backup must be stored in a main backup directory
target_dir = 'D:\\PYBackup' # 3. The files are backed up into a zip file
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the 7za command to put the files in a zip archive
zip_command = '7za.exe a {0} {1}'.format(target, ' '.join(source)) # Run the backup
if os.system(zip_command) == 0:
print ('Successful backup to ', target)
else:
print ('Backup Failed')

运行结果:

2.2 解决方案2

实现功能:

更好的文件名机制:使用时间作为文件名,而当前的日期作为目录名,存在在主备份目录中。这样做的优势:

(1)你的备份会以等级结构存储,因此它就更容易管理了。

(2)文件名的长度变短。

(3)采用各自独立的文件夹可以帮助你方便的检验你是否在每一天创建了备份。

代码如下所示:

 #! /usr/bin/python
# Filename: backup_ver2.py import os
import time # 1. The files and directories to be backed up are specified in a list
source = ['"D:\\QT\\py 1"','D:\\QT\\py2']
# Notice we had to use double quotes inside the string for names with spaces in it # 2. The backup must be stored in a main backup directory
target_dir = 'D:\\PYBackup' # Remember to change this to what you will be using # 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S') # Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print ('Successfully created directory',today) # The name of the zip file
target = today + os.sep + now + '.zip' # 5. We use the 7za command to put the files in a zip archive
zip_command = '7za.exe a {0} {1}'.format(target, ' '.join(source)) # Run the backup
if os.system(zip_command) == 0:
print ('Successful backup to ', target)
else:
print ('Backup Failed')

运行结果:

2.3 解决方案3

实现功能:

通过在zip归档名上附带一个用户提供的注释来提高备份的可理解性。

代码如下所示:

 #! /usr/bin/python
# Filename: backup_ver3.py import os
import time # 1. The files and directories to be backed up are specified in a list
source = ['"D:\\QT\\py 1"','D:\\QT\\py2']
# Notice we had to use double quotes inside the string for names with spaces in it # 2. The backup must be stored in a main backup directory
target_dir = 'D:\\PYBackup' # Remember to change this to what you will be using # 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file
comment = input ('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +\
comment.replace(' ', '_') + '.zip' # Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print ('Successfully created directory',today) # 5. We use the 7za command to put the files in a zip archive
zip_command = '7za.exe a {0} {1}'.format(target, ' '.join(source)) # Run the backup
if os.system(zip_command) == 0:
print ('Successful backup to ', target)
else:
print ('Backup Failed')

运行结果:

输入Backup

没有输入任何值,直接按回车

3. 总结

看到自己编写的程序能够运行并完成预期的功能,感觉挺爽!

Python,还没入门,还有好多的路要走,加油!

参考文献

[1] Swaroop, C.H.(著), Let it be!(译)(e-mail: 329974248@qq.com), A Byte of Python v1.92(for Python 3.0), 2011.7.9

[2] 7z, http://sparanoid.com/lab/7z/

[3] 7-zip 命令行版本(7-zip 9.20), http://downloads.sourceforge.net/sevenzip/7za920.zip

Python实例学习-文件备份的更多相关文章

  1. Python实现文件备份

    Python实现文件拷贝 2017年8月27日 1.实现目的 统一时间对服务器某文件夹内文件进行备份保存,如若备份成功则不提示任何错误,否则将以邮件的形式告知管理员,备份出错. 2.程序流程图 主要流 ...

  2. Python/CMD 文件备份

    1.使用Python压缩文件并另存 import zipfile, os #备份文件ZIP格式: folder 目标文件夹 : Targetfolder:另存地址 def backuptozip(fo ...

  3. Python检查 文件备份是否正常 云备份进程是否正常运行

    场景:服务器自动备份数据库文件,每两小时生成一个新备份文件,通过云备份客户端自动上传,需要每天检查是否备份成功. 实现:本脚本实现检查文件是否备份成功,进程是否正常运行,并且发送相关邮件提醒. #! ...

  4. python项目练习地址

    作者:Wayne Shi链接:http://www.zhihu.com/question/29372574/answer/88744491来源:知乎著作权归作者所有,转载请联系作者获得授权. 目前是3 ...

  5. 从0开始的Python学习013编写一个Python脚本

    通过之前的学习我们已经了解了Python的很多基础运用了,现在我们尝试着做一个有使用价值的小脚本. 问题 需求: 我想要一个可以给我备份重要文件的程序. 需求分析: 首先文件是有存储路径,文件的路径和 ...

  6. python项目推荐(转载知乎)

    作者:Wayne Shi链接:https://www.zhihu.com/question/29372574/answer/88744491来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商 ...

  7. Python代码样例列表

    扫描左上角二维码,关注公众账号 数字货币量化投资,回复“1279”,获取以下600个Python经典例子源码 ├─algorithm│       Python用户推荐系统曼哈顿算法实现.py│    ...

  8. Python输入输出及其他

    print用法 print会输出一个\n,也就是换行符,这样光标移动到了下一行行首,接着输出,之前已经通过stdout输出的东西依旧保留,而且保证我们在下面看到最新的输出结果.回车 \r 本义是光标重 ...

  9. Python知乎上推荐的项目

    原文地址:https://www.zhihu.com/question/29372574/answer/88744491 作者:Wayne Shi链接:https://www.zhihu.com/qu ...

随机推荐

  1. APP测试实用小工具

    1.ADB万能驱动 http://pan.baidu.com/s/1jIJPwhS 2.安卓手机屏幕共享 http://pan.baidu.com/s/1nv6ma1b 3.IOS手机屏幕共享 htt ...

  2. 对SIL9022/9024的配置

    这里只是记录下对SIL9022.9024配置的I2C的数据,没有具体的程序.程序可以参考数据来做.程序官网也可能有. start of decoding Write to 0x72 0xBC ? 0x ...

  3. shell腳本

    1.awk过滤重复行 awk '!a[$0]++{print $0}' 过滤重复行 awk '!a[$1]++{print $1}' 过滤第一列重复行 并只打印第一列 awk '!($1 in a){ ...

  4. MIS系统开发利器,实施、维护人员自定义报表的福音,AgileEAS.NET SOA平台动态报表指南

    一.前言 AgileEAS.NET SOA 中间件平台是一款基于基于敏捷并行开发思想和Microsoft .Net构件(组件)开发技术而构建的一个快速开发应用平台.用于帮助中小型软件企业建立一条适合市 ...

  5. AdaBoost算法分析与实现

    AdaBoost(自适应boosting,adaptive boosting)算法 算法优缺点: 优点:泛化错误率低,易编码,可用在绝大部分分类器上,无参数调整 缺点:对离群点敏感 适用数据类型:数值 ...

  6. PAT A 1022. Digital Library (30)【结构体排序检索】

    https://www.patest.cn/contests/pat-a-practise/1022 直接模拟, 输入,按id排序,检索 #include <iostream> #incl ...

  7. Linux学习笔记(2)-开机

    今天开始学习Linux系统. 打开虚拟机,输入密码后,令人激动的画面就蹦出来了-- Ubuntu的主要基调是橙色,给人一种蠢萌蠢萌的感觉,和Windows不同,它只在左边有一条任务栏,上面有些东西,搜 ...

  8. 【Oracle】oracle之listagg分析函数

    oracle分析函数——listagg篇 (1)使用listagg将多行数据合并到一行 例表: select deptno, ename from emp order by deptno, ename ...

  9. 【Unity3d游戏开发】unity3D OnTriggerEnter和OnCollisionEnter的一点个人心得(转载)

    此文为转载,因为最近在做U3D,有一些概念弄得不是很清楚,看到这篇博客讲的不错,就转载过来了,方便自己随时查看. ------------------------------------------- ...

  10. 【DP】HDU 1087

    HDU 1078 Super Jumping! Jumping! Jumping! 题意: 有这么个游戏,从start到end(自己决定在哪停下来)连续跳圈,中间不能空一个圈不跳,圈里的数字必须比你上 ...