A Byte of Python实例中的备份数据小程序第五版
初学Python看电子书A Byte of Python, 书中在讲到写个小程序备份数据,第五版要用python自带的模块来实现,即不用os.system(command)来调用操作系统上的zip命令来实现。在试着写第五版时,用到了dir(module),print(module.__doc__) 以及help(module)等命令,这些命令能快速获取到模块信息。
新建backup.py文件,敲入以下代码:
import os,time,zipfile
#待备份目录列表
source_dir = ["D:\\dev\\py"]
#备份目录
target_dir = "D:\\backup"
#按日期目录进行归档
today = target_dir + os.sep + time.strftime("%Y%m%d")
#按时间命名归档文件
now = time.strftime("%H%M%S")
#如果日期目录不存在,则新建目录
if not os.path.exists(today):
os.mkdir(today)
#为每个备份文件增加备注信息
comment = input("输入备注信息:")
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now+ \
"_" + comment.replace(" ", "_") + ".zip"
#开始备份,os.walk(dir)将遍历目录下的所有文件以及文件夹
with zipfile.ZipFile(target, "w") as myzip:
for root,dirs,files in os.walk(source_dir):
for file in files:
myzip.write(os.path.join(root, file))
myzip.close()
#第四版中调用zip命令进行备份
#zip_command = "zip -qr {0} {1}".format(target, source_dir)
#if os.system(zip_command) == 0:
#print("backup successful", target)
#else:
#print("backup failed")
页:
[1]