您的位置:首页 > 编程语言 > Python开发

python zipfile模块

2017-10-15 22:09 591 查看
虽然叫zipfile,但是除了zip之外,rar,war,jar这些压缩(或者打包)文件格式也都可以处理。

zipfile模块常用的一些操作和方法:

is_zipfile(filename)  

测试filename的文件,看它是否是个有效的zipfile

ZipFile(filename[,mode[,compression[,allowZip64]]])  

构造zipfile文件对象。mode可选r,w,a代表不同的打开文件的方式。compression指出这个zipfile用什么压缩方法,默认是ZIP_STORED,另一种选择是ZIP_DEFLATED。allowZip64是个bool型变量,当设置为True的时候就是说可以用来创建大小大于2G的zip文件,默认值是True

ZipInfo 

包含一个zip文件中的子文件的信息,字段包括filename(包括相对zip包的路径),date_time(一个时间元组,该子文件最后修改时间),compress_type(该子文件的压缩格式)等等。

1、压缩

f=zipfile.ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=False)

创建一个zip文件对象,压缩是需要把mode改为‘w’,这个是源码中的注释Open the ZIP file with mode read "r", write "w" or append "a",a为追加压缩,不会清空原来的zip

f.write(f(filename[,arcname[,compression_type]])  将zip外的文件filename写入到名为arcname的子文件中(当然arcname也是带有相对zip包的路径的),compression_type指定了压缩格式,也是ZIP_STORED或ZIP_DEFLATED。f的打开方式一定要是w或者a才能顺利写入文件。

将文件写入zip文件中,即将文件压缩

f.close()

将zip文件对象关闭,与open一样可以使用上下文with as

f.open(name[,mode[,pwd]])  获取一个子文件的文件对象,可以将其用来read,readline,write等等操作

def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))

zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
#print arcname
zf.write(tar,arcname)
zf.close()

2、解压

f.extract(name[,path[,pwd]])从zip中提取一个文件,将它放到指定的path下,pwd是密码,用于被加密的zip文件

f.extractall(path[,pwd])  将所有文件按照namelist中显示得那样的目录结构从当前zip中提取出来并放到path下。//这两个extract的path若不存在都会自动创建出来的,且这个path必须是个目录,解压时一定是把一个文件,包含其相对zip包路径的所有目录一起解压出来。总之有点坑,自己测试一下就知道了
<
1003f
/p>

def unzip_dir(zipfilename, unzipdirname):
fullzipfilename = os.path.abspath(zipfilename)
fullunzipdirname = os.path.abspath(unzipdirname)
print "Start to unzip file %s to folder %s ..." % (zipfilename, unzipdirname)
#Check input ...
if not os.path.exists(fullzipfilename):
print "Dir/File %s is not exist, Press any key to quit..." % fullzipfilename
inputStr = raw_input()
return
if not os.path.exists(fullunzipdirname):
os.mkdir(fullunzipdirname)
else:
if os.path.isfile(fullunzipdirname):
print "File %s is exist, are you sure to delet it first ? [Y/N]" % fullunzipdirname
while 1:
inputStr = raw_input()
if inputStr == "N" or inputStr == "n":
return
else:
if inputStr == "Y" or inuptStr == "y":
os.remove(fullunzipdirname)
print "Continue to unzip files ..."
break

#Start extract files ...
srcZip = zipfile.ZipFile(fullzipfilename, "r")
for eachfile in srcZip.namelist():
print "Unzip file %s ..." % eachfile
eachfilename = os.path.normpath(os.path.join(fullunzipdirname, eachfile))
eachdirname = os.path.dirname(eachfilename)
if not os.path.exists(eachdirname):
os.makedirs(eachdirname)
fd=open(eachfilename, "wb")
fd.write(srcZip.read(eachfile))
fd.close()
srcZip.close()
print "Unzip file succeed!"


高级应用 

1 zipfile.is_zipfile(filename) 

判断一个文件是不是压缩文件 

2 ZipFile.namelist() 

zip 解压出来的文件,当然未必只有一个;返回文件列表 ,内容是zip文件中所有子文件的path(相对于zip文件包而言的)。相当于是一个保存了zip内部目录结构的列表

3 ZipFile.open(name[, mode[, password]]) 

打开压缩文档中的某个文件

4 z.infolist()  

返回一个列表,内容是每个zip文件中子文件的ZipInfo对象,这个对象有上文中提到的那些字段

5 z.printdir()  

将zip文件的目录结构打印到stdout上,包括每个文件的path,修改时间和大小   

6 z.setpassword(psw)  

可以为zip文件设置默认密码

7 z.testzip()  

读取zip中的所有文件,验证他们的CRC校验和。返回第一个损坏文件的名称,如果所有文件都是完整的就返回None

if zipfile.is_zipfile('test.zip'): #is_zipfile() 判断是否似zip文件
f = zipfile.ZipFile('test.zip')
files = f.namelist() #namelist() 返回zip压缩包中的所有文件
print 'files:', files
mess = f.open('channel/readme.txt') #打开zip压缩包中的某个文件,可读可写
print 'mess:', mess.read()
f.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: