import zipfile, os
filename = 'text_02.zip'
z = zipfile.ZipFile(filename, 'w')
# 注意这里的第二个参数是w,这里的filename是压缩包的名字
#假设要把一个叫testdir中的文件全部添加到压缩包里(这里只添加一级子目录中的文件)
if os.path.isdir('./yaml_01.py'):
for d in os.listdir('./yaml_01.py'):
z.write('./yaml_01.py'+os.sep+d)
# close() 是必须调用的!
z.close()
for i in z.infolist():
print(i.file_size, i.header_offset)
biplist is a binary plist parser/generator for Python.
Binary Property List (plist) files provide a faster and smaller serialization format for property lists on OS X. This is a library for generating binary plists which can be read by OS X, iOS, or other clients.
This module requires Python 2.6 or higher or Python 3.4 or higher.
zipfile模块和biplist模块
zipfile模块:
zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个class就可以了。 ZipFile是主要的类,用来创建和读取zip文件,而ZipInfo是存储的zip文件的每个文件的信息的。
结果: 0 0 0 54
...(由于内容太多了省略下)
这里使用了z.infolist(), 它返回的就是压缩包内所有文件的信息,就是一个ZipInfo的列表。
一个ZipInfo对象中包含了压缩包内一个文件的信息,其中比较常用的是 filename, file_size, header_offset,
分别为文件名,文件大小,文件数据在压缩包中的偏移。
其实之前的z.namelist()就是读取的ZipInfo中的filename,组成一个 list返回的。
(1)从压缩包里解压缩出文件的方法是使用ZipFile的read方法
结果: ['Payload/', 'Payload/HLJClient.app/', 'Payload/HLJClient.app/084@2x.png', 'Payload/HLJClient.app/icon_file_trans_pressed@2x.png', 'Payload/HLJClient.app/sharemore_videovoip@2x.png', 'Payload/HLJClient.app/cMV2_henmanyi_normal@3x.png', ...(由于内容太多了省略下)]
这样就读取出z.namelist()中的文件,并且输出到屏幕,当然也可以把它存储到文件。
(2)下面是创建zip压缩包的方法,与读取的方法其实很类似的:
(3)想想还有一个问题,如果我把一个test/111.txt 添加到压缩包里之后我希望在包里它放到test22/111.txt怎么办呢?其实这个就是Python ZipFile模块的write方法中第二个参数的作用了。只需要这样调用:
(4)其他方法:
biplist模块:
利用下官方文档的介绍:
biplist
is a binary plist parser/generator for Python.Binary Property List (plist) files provide a faster and smaller serialization format for property lists on OS X. This is a library for generating binary plists which can be read by OS X, iOS, or other clients.
This module requires Python 2.6 or higher or Python 3.4 or higher.