python模块整理7-zipfile模块

官方文档:http://docs.python.org/library/zipfile.html#module-zipfile

如果考虑到跨平台,要考虑用zip压缩文件

一、压缩

使用zipfile模块将文件储存在 ZIP 文件里

向压缩档加入文件很简单, 将文件名, 文件在 ZIP 档中的名称传递给 write 方法即可.

write 方法的第三个可选参数用于控制是否使用压缩.默认为 zipfile.ZIP_STORED , 意味着只是将数据储存在档案里而不进行任何压缩.

如果安装了 zlib 模块, 那么就可以使用 zipfile.ZIP_DEFLATED 进行压缩.

import zipfile

import glob, os

file = zipfile.ZipFile("test.zip", "w") # 打开压缩包,写方式

for name in glob.glob("bin/*"): # 匹配samples目录下所有文件

file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) #将文件写入到压缩包内

file.close()

注意这个压缩是bin目录下的文件和目录都压缩了

二、解压

1、解压压缩包中指定的文件到指定的目录,如果有密码输入密码

ZipFile.extract(member[, path[, pwd]])

Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object). Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files

2、解压所有文件,到指定目录[如果需要],指定密码如果需要

ZipFile.extractall([path[, members[, pwd]]])

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files

>>> file=zipfile.ZipFile('/root/test1.zip','r')

>>> file.extractall('/tmp/zipdit')

>>> file.close()

三、从 ZIP 文件中读取数据

有些时候,我们不想解压,想直接读取压缩中一个文件的内容

调用 read 方法就可以从 ZIP 文档中读取数据. 它接受一个文件名作为参数, 返回字符串

import zipfile

file = zipfile.ZipFile("samples/sample.zip", "r") # 打开压缩包

for name in file.namelist(): #列出压缩包内文件名称

data = file.read(name) # 读取文件到data

print name, len(data), repr(data[:10]) # 输出文件对象数量及内容

sample.txt 302 'We will pe'

sample.jpg 4762 '\377\330\377\340\000\020JFIF'

四、读取压缩文件信息

1、列出压缩包内文件名

for name in file.namelist():

print name,

2、列出包文件信息

file = zipfile.ZipFile("test.zip", "r")

for info in file.infolist():

print info.filename, info.date_time, info.file_size, info.compress_size

需要注意的是默认情况下zip压缩原文件还保留,而gzip不保留

园子里一个朋友整理的不错

http://www.cnblogs.com/zhengyuxin/articles/1956178.html