python学习笔记

上一篇 / 下一篇  2009-08-03 10:53:10 / 个人分类:python学习

今天学习了在WINDOWS上压缩一个文件夹,记录下来,以防忘了:

import os
import time
import zipfile
from os.path import join

def zipfolder(foldername,filename):
    '''
        zip folder foldername and all its subfiles and folders into
        a zipfile named filename
    '''
    empty_dirs=[]
    zip=zipfile.ZipFile(filename,'w',zipfile.ZIP_DEFLATED)
    for root,dirs,files in os.walk(foldername):
        empty_dirs.extend([dir for dir in dirs if os.listdir(join(root,dir))==[]])
        for filename in files:
            print "compressing",join(root,filename).encode("gbk")
            zip.write(join(root,filename).encode("gbk"))
    for dir in empty_dirs:
        zif=zipfile.ZipInfo(join(root,dir).encode("gbk"+"/"))
        zip.writestr(zif,"")
    zip.close()
    print "Finish compressing"
   

# 1. The files and directories to be backed up are specified in a list.
source = ['D:\\MLES\\database', 'D:\\test']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory
target_dir = 'D:\\temp' # Remember to change this to what you will be using

# 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 + time.strftime('%Y%m%d%H%M%S') + '.zip'

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
#zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
m=len(source)-1
for i in range(0,m):
    target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
    zipfolder(source[i],target)


TAG: Python python zipfile

 

评分:0

我来说两句

honghong806

honghong806

我测试,我快乐

日历

« 2024-04-28  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 3660
  • 日志数: 9
  • 文件数: 1
  • 建立时间: 2009-05-20
  • 更新时间: 2009-08-26

RSS订阅

Open Toolbar