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()
再来查看官方文档:
-
The numeric constant for an uncompressed archive member.
zipfile.
ZIP_STORED
-
The numeric constant for the usual ZIP compression method. This requires the
zlib
module. No other compression methods are currently supported.
zipfile.
ZIP_DEFLATED
难怪我压缩发现文件越来越大了
但是zipfile用的默认压缩算法是zlib,目前仅支持这个。
解压缩:
解压缩就比较简单了
-
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 aZipInfo
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
becomesfoo/bar
on Unix, andC:\foo\bar
becomesfoo\bar
on Windows. And all".."
components in a member filename will be removed, e.g.:../../foo../../ba..r
becomesfoo../ba..r
. On Windows illegal characters (:
,<
,>
,|
,"
,?
, and*
) replaced by underscore (_
).
ZipFile.
extract
(
member
[,
path
[,
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.
ZipFile.
extractall
(
[
path
[,
members
[,
pwd
]
]
]
)
说明了读文档的能力还是不够细!要加强!!!