简明python教程使用zipfile方法创建归档文件

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两位大大。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值