python小白,正在使用《简明python教程》自学python。此文为书中“解决问题”一章后的使用zipfile创建归档文件本人的程序,希望可以帮助到需要帮助的人。
成文参考了《简明python教程》,
http://blog.csdn.net/b_h_l/article/details/9406675以及
http://www.51testing.com/html/87/15091687-3686445.html。特此注明出处。若有侵权行为,请速与我联系,谢谢。
代码如下:
# coding=gbk
import os
import time
import sys
import zipfile
# 1. 需备份的文件与目录将被指定在一个列表中
a=sys.argv[1]
sources = ['F:\\source']
sources.append(a)
# 此处需注意:必须在字符串中使用双引号用以括起其中包含空格的名称。
print(sources)
# 2. 备份文件必须存储在一个主备份目录中
target_dir = 'G:\\Backup'
# 3.备份文件将打包压缩成zip
# 4.zip的文件名由当前日期与时间构成
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
# 添加一条来自用户的注释以创建zip的文件名
comment = input('Enter a comment --> ')
# 检查是否有评论键入
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.zip'
#如果目标目录还不存在,则进行创建
if not os.path.exists(target_dir):
os.mkdir(target_dir) #创建目录
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
# 运行备份
print('Running:')
z = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
for source in sources:
for dirpath, dirnames, filenames in os.walk(source):
for filename in filenames:
directory = os.path.join(dirpath,filename)
z.write(directory)
names=z.namelist()
print(names)
z.close()
此程序可实现将内置文件夹与指定文件夹打包成以时间+用户评论命名的.zip文件。大部分代码来自《简明python教程》,运行备份部分参考了
http://blog.csdn.net/b_h_l/article/details/9406675。若对
for dirpath, dirnames, filenames in os.walk(source):一句有疑问,则可移步
http://www.51testing.com/html/87/15091687-3686445.html。非常感谢
b_h_l和南瓜demi两位大大。