12.4. zipfile — 使用ZIP存档

1.6 新版功能.

源代码: Lib/zipfile.py


ZIP 文件格式是一个常用的归档与压缩标准。 这个模块提供了创建、读取、写入、添加及列出 ZIP 文件的工具。 任何对此模块的进阶使用都将需要理解此格式,其定义参见 PKZIP 应用程序笔记

This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C.

这个模块定义了以下内容:

exception zipfile.BadZipfile

The error raised for bad ZIP files (old name: zipfile.error).

exception zipfile.LargeZipFile

当 ZIP 文件需要 ZIP64 功能但是未启用时会抛出此错误。

class zipfile.ZipFile

用于读写 ZIP 文件的类。 欲了解构造函数的描述,参阅段落 ZipFile 对象

class zipfile.PyZipFile

用于创建包含 Python 库的 ZIP 归档的类。

class zipfile.ZipInfo([filename[, date_time]])

用于表示档案内一个成员信息的类。 此类的实例会由 ZipFile 对象的 getinfo()infolist() 方法返回。 大多数 zipfile 模块的用户都不必创建它们,只需使用此模块所创建的实例。 filename 应当是档案成员的全名,date_time 应当是包含六个字段的描述最近修改时间的元组;这些字段的描述请参阅 ZipInfo 对象

zipfile.is_zipfile(filename)

根据文件的 Magic Number,如果 filename 是一个有效的 ZIP 文件则返回 True,否则返回 Falsefilename 也可能是一个文件或类文件对象。

在 2.7 版更改: 支持文件或类文件对象。

zipfile.ZIP_STORED

未被压缩的归档成员的数字常数。

zipfile.ZIP_DEFLATED

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

参见

PKZIP 应用程序笔记

Phil Katz 编写的 ZIP 文件格式文档,此格式和使用的算法的创建者。

Info-ZIP 主页

有关 Info-ZIP 项目的 ZIP 存档程序和开发库的信息。

12.4.1. ZipFile 对象

class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])

Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe).

在 2.6 版更改: If mode is a and the file does not exist at all, it is created.

compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib module is not available, RuntimeError is also raised. The default is ZIP_STORED. If allowZip64 is True zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If it is false (the default) zipfile will raise an exception when the ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default zip and unzip commands on Unix (the InfoZIP utilities) don’t support these extensions.

在 2.7.1 版更改: If the file is created with mode 'a' or 'w' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.

ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

2.7 新版功能: 添加了将 ZipFile 用作上下文管理员的功能。

ZipFile.close()

关闭归档文件。 你必须在退出程序之前调用 close() 否则将不会写入关键记录数据。

ZipFile.getinfo(name)

返回一个 ZipInfo 对象,其中包含有关归档成员 name 的信息。 针对一个目前并不包含于归档中的名称调用 getinfo() 将会引发 KeyError

ZipFile.infolist()

返回一个列表,其中包含每个归档成员的 ZipInfo 对象。 如果是打开一个现有归档则这些对象的排列顺序与它们对应条目在磁盘上的实际 ZIP 文件中的顺序一致。

ZipFile.namelist()

返回按名称排序的归档成员列表。

ZipFile.open(name[, mode[, pwd]])

Extract a member from the archive as a file-like object (ZipExtFile). name is the name of the file in the archive, or a ZipInfo object. The mode parameter, if included, must be one of the following: 'r' (the default), 'U', or 'rU'. Choosing 'U' or 'rU' will enable universal newline support in the read-only object. pwd is the password used for encrypted files. Calling open() on a closed ZipFile will raise a RuntimeError.

注解

The file-like object is read-only and provides the following methods: read(), readline(), readlines(), __iter__(), next().

注解

If the ZipFile was created by passing in a file-like object as the first argument to the constructor, then the object returned by open() shares the ZipFile’s file pointer. Under these circumstances, the object returned by open() should not be used after any additional operations are performed on the ZipFile object. If the ZipFile was created by passing in a string (the filename) as the first argument to the constructor, then open() will create a new file object that will be held by the ZipExtFile, allowing it to operate independently of the ZipFile.

注解

open(), read()extract() 方法可接受文件名或 ZipInfo 对象。 当尝试读取一个包含重复名称成员的 ZIP 文件时你将发现此功能很有好处。

2.6 新版功能.

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.6 新版功能.

注解

如果一个成员文件名为绝对路径,则将去掉驱动器/UNC共享点和前导的(反)斜杠,例如: ///foo/bar 在 Unix 上将变为 foo/bar,而 C:\foo\bar 在 Windows 上将变为 foo\bar。 并且一个成员文件名中的所有 ".." 都将被移除,例如: ../../foo../../ba..r 将变为 foo../ba..r。 在 Windows 上非法字符 (:, <, >, |, ", ?, and *) 会被替换为下划线 (_)。

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

从归档中提取出所有成员放入当前工作目录。 path 指定一个要提取到的不同目录。 members 为可选项且必须为 namelist() 所返回列表的一个子集。 pwd 是用于解密文件的密码。

警告

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".

在 2.7.4 版更改: The zipfile module attempts to prevent that. See extract() note.

2.6 新版功能.

ZipFile.printdir()

将归档的目录表打印到 sys.stdout

ZipFile.setpassword(pwd)

设置 pwd 为用于提取已加密文件的默认密码。

2.6 新版功能.

ZipFile.read(name[, pwd])

Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a closed ZipFile will raise a RuntimeError.

在 2.6 版更改: pwd was added, and name can now be a ZipInfo object.

ZipFile.testzip()

Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None. Calling testzip() on a closed ZipFile will raise a RuntimeError.

ZipFile.write(filename[, arcname[, compress_type]])

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. The archive must be open with mode 'w' or 'a' – calling write() on a ZipFile created with mode 'r' will raise a RuntimeError. Calling write() on a closed ZipFile will raise a RuntimeError.

注解

There is no official file name encoding for ZIP files. If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets all file names as encoded in CP437, also known as DOS Latin.

注解

归档名称应当是基于归档根目录的相对路径,也就是说,它们不应以路径分隔符开头。

注解

如果 arcname (或 filename,如果 arcname 未给出) 包含一个空字节,则归档中该文件的名称将在空字节位置被截断。

ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])

Write the string bytes to the archive; zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a name, the date and time is set to the current date and time. The archive must be opened with mode 'w' or 'a' – calling writestr() on a ZipFile created with mode 'r' will raise a RuntimeError. Calling writestr() on a closed ZipFile will raise a RuntimeError.

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance).

注解

当传入一个 ZipInfo 实例作为 zinfo_or_arcname 形参时,所使用的压缩方法将为在给定的 ZipInfo 实例的 compress_type 成员中指定的方法。 默认情况下,ZipInfo 构造器将将此成员设为 ZIP_STORED

在 2.7 版更改: compress_type 参数。

以下数据属性也是可用的:

ZipFile.debug

要使用的调试输出等级。 这可以设为从 0 (默认无输出) 到 3 (最多输出) 的值。 调试信息会被写入 sys.stdout

ZipFile.comment

The comment text associated with the ZIP file. If assigning a comment to a ZipFile instance created with mode ‘a’ or ‘w’, this should be a string no longer than 65535 bytes. Comments longer than this will be truncated in the written archive when close() is called.

12.4.2. PyZipFile 对象

The PyZipFile constructor takes the same parameters as the ZipFile constructor. Instances have one method in addition to those of ZipFile objects.

PyZipFile.writepy(pathname[, basename])

Search for files *.py and add the corresponding file to the archive. The corresponding file is a *.pyo file if available, else a *.pyc file, compiling if necessary. If the pathname is a file, the filename must end with .py, and just the (corresponding *.py[co]) file is added at the top level (no path information). If the pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.py[co] are added at the top level. If the directory is a package directory, then all *.py[co] are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively. basename is intended for internal use only. The writepy() method makes archives with file names like this:

string.pyc                                # Top level name
test/__init__.pyc                         # Package directory
test/test_support.pyc                          # Module test.test_support
test/bogus/__init__.pyc                   # Subpackage directory
test/bogus/myfile.pyc                     # Submodule test.bogus.myfile

12.4.3. ZipInfo 对象

ZipInfo 类的实例会通过 getinfo()ZipFile 对象的 infolist() 方法返回。 每个对象将存储关于 ZIP 归档的一个成员的信息。

Instances have the following attributes:

ZipInfo.filename

归档中的文件名称。

ZipInfo.date_time

上次修改存档成员的时间和日期。这是六个值的元组:

索引

0

Year (>= 1980)

1

月(1为基数)

2

月份中的日期(1为基数)

3

小时(0为基数)

4

分钟(0为基数)

5

秒(0为基数)

注解

ZIP文件格式不支持1980年以前的时间戳。

ZipInfo.compress_type

归档成员的压缩类型。

ZipInfo.comment

Comment for the individual archive member.

ZipInfo.extra

Expansion field data. The PKZIP Application Note contains some comments on the internal structure of the data contained in this string.

ZipInfo.create_system

创建 ZIP 归档所用的系统。

ZipInfo.create_version

创建 ZIP 归档所用的 PKZIP 版本。

ZipInfo.extract_version

需要用来提取归档的 PKZIP 版本。

ZipInfo.reserved

必须为零。

ZipInfo.flag_bits

ZIP 标志位。

ZipInfo.volume

文件中的分卷号。

ZipInfo.internal_attr

内部属性。

ZipInfo.external_attr

外部文件属性。

ZipInfo.header_offset

文件头的字节偏移量。

ZipInfo.CRC

未压缩文件的 CRC-32。

ZipInfo.compress_size

已压缩数据的大小。

ZipInfo.file_size

未压缩文件的大小。

12.4.4. 命令行界面

zipfile 模块提供了简单的命令行接口用于与 ZIP 归档的交互。

如果你想要创建一个新的 ZIP 归档,请在 -c 选项后指定其名称然后列出应当被包含的文件名:

$ python -m zipfile -c monty.zip spam.txt eggs.txt

传入一个字典也是可接受的:

$ python -m zipfile -c monty.zip life-of-brian_1979/

如果你想要将一个 ZIP 归档提取到指定的目录,请使用 -e 选项:

$ python -m zipfile -e monty.zip target-dir/

对于一个 ZIP 归档中的文件列表,请使用 -l 选项:

$ python -m zipfile -l monty.zip

12.4.4.1. 命令行选项

-l <zipfile>

列出一个 zipfile 中的文件名。

-c <zipfile> <source1> ... <sourceN>

基于源文件创建 zipfile。

-e <zipfile> <output_dir>

将 zipfile 提取到目标目录中。

-t <zipfile>

检测 zipfile 是否有效。