python用zipfile模块打包文件或是目录、解压zip文件实例,不过好像解压对中文的支持不太好,不包含中文的话没有问题,有懂的朋友可以帮助完善一下。
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- from zipfile import *
- import zipfile
- #解压zip文件
- def unzip():
- source_zip="c:\\update\\SW_Servers_20120815.zip"
- target_dir="c:\\update\\"
- myzip=ZipFile(source_zip)
- myfilelist=myzip.namelist()
- for name in myfilelist:
- f_handle=open(target_dir+name,"wb")
- f_handle.write(myzip.read(name))
- f_handle.close()
- myzip.close()
- #添加文件到已有的zip包中
- def addzip():
- f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
- f.write('file_to_add.py')
- f.close()
- #把整个文件夹内的文件打包
- def adddirfile():
- f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
- startdir = "c:\\mydirectory"
- for dirpath, dirnames, filenames in os.walk(startdir):
- for filename in filenames:
- f.write(os.path.join(dirpath,filename))
- f.close()
本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1045577,如需转载请自行联系原作者