您的位置:首页 > 其它

zipfile的压缩和解压缩

2016-01-27 16:56 113 查看
zipfile是python提供的内置的压缩方法

可以对zip文件进行压缩和解压缩

压缩:

zf = ZipFile("out.zip", "w", mode=zipfile.ZIP_STORED)

zf.write("文件全路径", "归档文件全路径(也就是写入压缩包的相对路径)")

说明:

zipfile.ZIP_STORED是默认压缩方式,其实只是存储,并不进行内容压缩

如果要使用压缩,必须要import zlib库才可以

如下:

import zipfile
try:
import zlib
mode= zipfile.ZIP_DEFLATED
except:
mode= zipfile.ZIP_STORED

zip= zipfile.ZipFile('zipfilename', 'w', mode)
zip.write(item)
zip.close()


再来查看官方文档:

zipfile.
ZIP_STORED


The numeric constant for an uncompressed archive member.

zipfile.
ZIP_DEFLATED


The numeric constant for the usual ZIP compression method. This requires the
zlib
module. No other compression methods are currently supported.

难怪我压缩发现文件越来越大了

但是zipfile用的默认压缩算法是zlib,目前仅支持这个。

解压缩:

解压缩就比较简单了

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.

Returns the normalized path created (a directory or new file).

New in version 2.6.

Note
If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.:
///foo/bar
becomes
foo/bar
on Unix, and
C:\foo\bar
becomes
foo\bar
on Windows. And all
".."
components in a member filename will be removed, e.g.:
../../foo../../ba..r
becomes
foo../ba..r
. On Windows illegal characters (
:
,
<
,
>
,
|
,
"
,
?
, and
*
) replaced by underscore (
_
).

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.

说明了读文档的能力还是不够细!要加强!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: