zipfile模块简介

zipfile模块()用于压缩文件成zip及解压zip文件,模块介绍如下。

·zipfile.ZipFile(file,mode)openaZIPfilewherefilecanbeeitherapathtoafileorafile-likeobject.modecanberead“r”,write“w”,orappend“a”以某种模式打开ZIP文档.默认值为’r’表示读已经存在的zip文件,‘w’表示新建一个zip文档或覆盖一个存在的同名zip文档,‘a’表示将数据附加到一个现存的zip文档中。

classzipfile.ZipFile的里面有如下模块:

·ZipFile.namelist()returnalistofarchivemembersbyname.返回一个列表包含zipfile里面的文件

·ZipFile.close()closethearchivefile当解压完zip文件以后关闭zipfile.

·ZipFile.extractall(self,path=None,members=None,pwd=None)Extractallmembersfromthearchivetothecurrentworkingdirectory.Pathspecifiedadifferentdirectorytoextractto.Memberisoptionalandmustbesubsetofthelistreturnedbynamelist().

解压全部文件到当前路径,也可以加压到指定路径。

·ZipFile.extract(self,member,path=None,pwd=None)extractamemberfromthearchivetothecurrentworkingdirectorymembermustbeitsfullname.ZIP文件里解压一个文件到当前路径,该文件必须以全名给定。

·ZipFile.setpassword(pwd)setpwdasdefaultpasswordtoextractencryptedfiles.设置一个默认密码用于解压文件。

·ZipFile.write(filename)writethefilenamedfilenametothearchive.将文件写入zip文档。

代码:

·压缩文件成zip包(pyhon是先创建一个空zip文件,在把需要zip的文件一一传进去)

import zipfile
import sys
import os
filepath = sys.argv[1]
outputpath = sys.argv[2]
os.chdir(filepath)
filelist = os.listdir(filepath) # list the files need to achieve
zipfilename = filepath.split("/")[-1] #fetch the last name of path as zipfile name
ZipFileobj = zipfile.ZipFile(filepath+"/"+ zipfilename +".zip", 'w') #create a zip file
for files in filelist:# use “for” to add files into zip file
ZipFileobj.write(files)
ZipFileobj.close()
print "zipfile already created!"

·解压zip

import zipfile
import sys
zipfilepath = sys.argv[1]
outputpath = sys.argv[2]
print zipfilepath
zipfiles = zipfile.ZipFile(zipfilepath, "r")
zipfiles.extractall(outputpath)
zipfiles.close()