zipfile --- 使用ZIP存档

源代码: Lib/zipfile.py


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

此模块目前不能处理分卷 ZIP 文件。它可以处理使用 ZIP64 扩展(超过 4 GB 的 ZIP 文件)的 ZIP 文件。它支持解密 ZIP 归档中的加密文件,但是目前不能创建一个加密的文件。解密非常慢,因为它是使用原生 Python 而不是 C 实现的。

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

exception zipfile.BadZipFile

为损坏的 ZIP 文件抛出的错误。

3.2 新版功能.

exception zipfile.BadZipfile

BadZipFile 的别名,与旧版本 Python 保持兼容性。

3.2 版后已移除.

exception zipfile.LargeZipFile

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

class zipfile.ZipFile

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

class zipfile.Path

用于 zip 文件的兼容 pathlib 的包装器。 详情参见 Path Objects

3.8 新版功能.

class zipfile.PyZipFile

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

class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))

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

zipfile.is_zipfile(filename)

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

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

zipfile.ZIP_STORED

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

zipfile.ZIP_DEFLATED

常用的 ZIP 压缩方法的数字常数。需要 zlib 模块。

zipfile.ZIP_BZIP2

BZIP2 压缩方法的数字常数。需要 bz2 模块。

3.3 新版功能.

zipfile.ZIP_LZMA

LZMA 压缩方法的数字常数。需要 lzma 模块。

3.3 新版功能.

注解

ZIP 文件格式规范包括自 2001 年以来对 bzip2 压缩的支持,以及自 2006 年以来对 LZMA 压缩的支持。但是,一些工具(包括较旧的 Python 版本)不支持这些压缩方法,并且可能拒绝完全处理 ZIP 文件,或者无法提取单个文件。

参见

PKZIP 应用程序笔记

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

Info-ZIP 主页

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

ZipFile 对象

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)

打开一个 ZIP 文件,file 为一个指向文件的路径(字符串),一个类文件对象或者一个 path-like object

形参 mode 应当为 'r' 来读取一个存在的文件,'w' 来截断并写入新的文件, 'a' 来添加到一个存在的文件,或者 'x' 来仅新建并写入新的文件。如果 mode'x' 并且 file 指向已经存在的文件,则抛出 FileExistsError。如果 mode'a'file 为已存在的文件,则格外的文件将被加入。如果 file 不指向 ZIP 文件,之后一个新的 ZIP 归档将被追加为此文件。这是为了将 ZIP 归档添加到另一个文件(例如 python.exe)。如果 mode'a' 并且文件不存在, 则会新建。如果 mode'r''a', 则文件应当可定位。

compression 是在写入归档时要使用的 ZIP 压缩方法,应为 ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2ZIP_LZMA;不可识别的值将导致引发 NotImplementedError。 如果指定了 ZIP_DEFLATED, ZIP_BZIP2ZIP_LZMA 但相应的模块 (zlib, bz2lzma) 不可用,则会引发 RuntimeError。 默认值为 ZIP_STORED

如果 allowZip64True (默认值) 则当 zipfile 大于 4 GiB 时 zipfile 将创建使用 ZIP64 扩展的 ZIP 文件。 如果该参数为 false 则当 ZIP 文件需要 ZIP64 扩展时 zipfile 将引发异常。

compresslevel 形参控制在将文件写入归档时要使用的压缩等级。 当使用 ZIP_STOREDZIP_LZMA 时无压缩效果。 当使用 ZIP_DEFLATED 时接受整数 09 (更多信息参见 zlib)。 当使用 ZIP_BZIP2 时接受整数 19 (更多信息参见 bz2)。

strict_timestamps 参数在设为 False 时允许压缩早于 1980-01-01 的文件,代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于 2107-12-31 的文件发生,时间戳也会被设为该上限值。

如果创建文件时使用 'w', 'x''a' 模式并且未向归档添加任何文件就执行了 closed,则会将适当的空归档 ZIP 结构写入文件。

ZipFile 也是一个上下文管理器,因此支持 with 语句。 在这个示例中,myzip 将在 with 语句块执行完成之后被关闭 --- 即使是发生了异常:

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

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

在 3.3 版更改: 添加了对 bzip2lzma 压缩的支持。

在 3.4 版更改: 默认启用 ZIP64 扩展。

在 3.5 版更改: 添加了对不可查找数据流的支持。 并添加了对 'x' 模式的支持。

在 3.6 版更改: 在此之前,对于不可识别的压缩值将引发普通的 RuntimeError

在 3.6.2 版更改: file 形参接受一个 path-like object

在 3.7 版更改: 添加了 compresslevel 形参。

3.8 新版功能: strict_timestamps 仅限关键字参数

ZipFile.close()

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

ZipFile.getinfo(name)

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

ZipFile.infolist()

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

ZipFile.namelist()

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

ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)

以二进制文件类对象的形式访问一个归档成员。 name 可以是归档内某个文件的名称也可以是某个 ZipInfo 对象。 如果包含了 mode 形参,则它必须为 'r' (默认值) 或 'w'pwd 为用于解密已加密 ZIP 文件的密码。

open() 也是一个上下文管理器,因此支持 with 语句:

with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())

如果 mode'r' 则文件类对象 (ZipExtFile) 将为只读并且提供下列方法: read(), readline(), readlines(), seek(), tell(), __iter__(), __next__()。 这些对象可独立于 ZipFile 进行操作。

如果 mode='w' 则返回一个可写入的文件句柄,它将支持 write() 方法。 当一个可写入的文件句柄被打开时,尝试读写 ZIP 文件中的其他文件将会引发 ValueError

当写入一个文件时,如果文件大小不能预先确定但是可能超过 2 GiB,可传入 force_zip64=True 以确保标头格式能够支持超大文件。 如果文件大小可以预先确定,则在构造 ZipInfo 对象时应设置 file_size,并将其用作 name 形参。

注解

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

在 3.6 版更改: 移除了对 mode='U' 的支持。 请使用 io.TextIOWrapper 以在 universal newlines 模式中读取已压缩的文本文件。

在 3.6 版更改: open() 现在可以被用来配合 mode='w' 选项来将文件写入归档。

在 3.6 版更改: 在已关闭的 ZipFile 上调用 open() 将引发 ValueError。 在之前的版本中则会引发 RuntimeError

ZipFile.extract(member, path=None, pwd=None)

从归档中提取出一个成员放入当前工作目录;member 必须为成员的完整名称或 ZipInfo 对象。 成员的文件信息会尽可能精确地被提取。 path 指定一个要提取到的不同目录。 member 可以是一个文件名或 ZipInfo 对象。 pwd 是用于解密文件的密码。

返回所创建的经正规化的路径(对应于目录或新文件)。

注解

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

在 3.6 版更改: 在已关闭的 ZipFile 上调用 extract() 将引发 ValueError。 在之前的版本中则将引发 RuntimeError

在 3.6.2 版更改: path 形参接受一个 path-like object

ZipFile.extractall(path=None, members=None, pwd=None)

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

警告

绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有可能在 path 之外创建文件,例如某些成员具有以 "/" 开始的文件名或带有两个点号 ".." 的文件名。 此模块会尝试防止这种情况。 参见 extract() 的注释。

在 3.6 版更改: 在已关闭的 ZipFile 上调用 extractall() 将引发 ValueError。 在之前的版本中则将引发 RuntimeError

在 3.6.2 版更改: path 形参接受一个 path-like object

ZipFile.printdir()

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

ZipFile.setpassword(pwd)

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

ZipFile.read(name, pwd=None)

返回归档中文件 name 的字节数据。 name 是归档中文件的名称,或是一个 ZipInfo 对象。 归档必须以读取或追加方式打开。 pwd 为用于已加密文件的密码,并且如果指定该参数则它将覆盖通过 setpassword() 设置的默认密码。 on a ZipFile that uses a compression method 在使用 ZIP_STORED , ZIP_DEFLATED, ZIP_BZIP2ZIP_LZMA 以外的压缩方法的 ZipFile 上调用 read() 将引发 NotImplementedError。 如果相应的压缩模块不可用也会引发错误。

在 3.6 版更改: 在已关闭的 ZipFile 上调用 read() 将引发 ValueError。 在之前的版本中则会引发 RuntimeError

ZipFile.testzip()

读取归档中的所有文件并检查它们的 CRC 和文件头。 返回第一个已损坏文件的名称,在其他情况下则返回 None

在 3.6 版更改: 在已关闭的 ZipFile 上调用 testzip() 将引发 ValueError。 在之前的版本中则将引发 RuntimeError

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)

将名为 filename 的文件写入归档,给予的归档名为 arcname (默认情况下将与 filename 一致,但是不带驱动器盘符并会移除开头的路径分隔符)。 compress_type 如果给出,它将覆盖作为构造器 compression 形参对于新条目所给出的值。 类似地,compresslevel 如果给出也将覆盖构造器。 归档必须使用 'w', 'x''a' 模式打开。

注解

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

注解

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

在 3.6 版更改: 在使用 'r' 模式创建的 ZipFile 或已关闭的 ZipFile 上调用 write() 将引发 ValueError。 在之前的版本中则会引发 RuntimeError

ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)

Write a file into the archive. The contents is data, which may be either a str or a bytes instance; if it is a str, it is encoded as UTF-8 first. 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', 'x' or 'a'.

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). Similarly, compresslevel will override the constructor if given.

注解

When passing a ZipInfo instance as the zinfo_or_arcname parameter, the compression method used will be that specified in the compress_type member of the given ZipInfo instance. By default, the ZipInfo constructor sets this member to ZIP_STORED.

在 3.2 版更改: compress_type 参数。

在 3.6 版更改: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

The following data attributes are also available:

ZipFile.filename

Name of the ZIP file.

ZipFile.debug

The level of debug output to use. This may be set from 0 (the default, no output) to 3 (the most output). Debugging information is written to sys.stdout.

ZipFile.comment

The comment associated with the ZIP file as a bytes object. If assigning a comment to a ZipFile instance created with mode 'w', 'x' or 'a', it should be no longer than 65535 bytes. Comments longer than this will be truncated.

Path Objects

class zipfile.Path(root, at='')

Construct a Path object from a root zipfile (which may be a ZipFile instance or file suitable for passing to the ZipFile constructor).

at specifies the location of this Path within the zipfile, e.g. 'dir/file.txt', 'dir/', or ''. Defaults to the empty string, indicating the root.

Path objects expose the following features of pathlib.Path objects:

Path objects are traversable using the / operator.

Path.name

The final path component.

Path.open(*, **)

Invoke ZipFile.open() on the current path. Accepts the same arguments as ZipFile.open().

Path.iterdir()

Enumerate the children of the current directory.

Path.is_dir()

Return True if the current context references a directory.

Path.is_file()

Return True if the current context references a file.

Path.exists()

Return True if the current context references a file or directory in the zip file.

Path.read_text(*, **)

Read the current file as unicode text. Positional and keyword arguments are passed through to io.TextIOWrapper (except buffer, which is implied by the context).

Path.read_bytes()

Read the current file as bytes.

PyZipFile Objects

The PyZipFile constructor takes the same parameters as the ZipFile constructor, and one additional parameter, optimize.

class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)

3.2 新版功能: The optimize parameter.

在 3.4 版更改: 默认启用 ZIP64 扩展。

Instances have one method in addition to those of ZipFile objects:

writepy(pathname, basename='', filterfunc=None)

Search for files *.py and add the corresponding file to the archive.

If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary.

If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary.

If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If 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 *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order.

basename is intended for internal use only.

filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them:

>>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
...     fn = os.path.basename(s)
...     return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)

The writepy() method makes archives with file names like this:

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

3.4 新版功能: The filterfunc parameter.

在 3.6.2 版更改: The pathname parameter accepts a path-like object.

在 3.7 版更改: Recursion sorts directory entries.

ZipInfo Objects

Instances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive.

There is one classmethod to make a ZipInfo instance for a filesystem file:

classmethod ZipInfo.from_file(filename, arcname=None, *, strict_timestamps=True)

Construct a ZipInfo instance for a file on the filesystem, in preparation for adding it to a zip file.

filename should be the path to a file or directory on the filesystem.

If arcname is specified, it is used as the name within the archive. If arcname is not specified, the name will be the same as filename, but with any drive letter and leading path separators removed.

strict_timestamps 参数在设为 False 时允许压缩早于 1980-01-01 的文件,代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于 2107-12-31 的文件发生,时间戳也会被设为该上限值。

3.6 新版功能.

在 3.6.2 版更改: The filename parameter accepts a path-like object.

3.8 新版功能: strict_timestamps 仅限关键字参数

Instances have the following methods and attributes:

ZipInfo.is_dir()

Return True if this archive member is a directory.

This uses the entry's name: directories should always end with /.

3.6 新版功能.

ZipInfo.filename

Name of the file in the archive.

ZipInfo.date_time

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

索引

0

Year (>= 1980)

1

月(1为基数)

2

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

3

小时(0为基数)

4

分钟(0为基数)

5

秒(0为基数)

注解

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

ZipInfo.compress_type

Type of compression for the archive member.

ZipInfo.comment

Comment for the individual archive member as a bytes object.

ZipInfo.extra

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

ZipInfo.create_system

System which created ZIP archive.

ZipInfo.create_version

PKZIP version which created ZIP archive.

ZipInfo.extract_version

PKZIP version needed to extract archive.

ZipInfo.reserved

必须为零。

ZipInfo.flag_bits

ZIP 标志位。

ZipInfo.volume

Volume number of file header.

ZipInfo.internal_attr

Internal attributes.

ZipInfo.external_attr

External file attributes.

ZipInfo.header_offset

Byte offset to the file header.

ZipInfo.CRC

CRC-32 of the uncompressed file.

ZipInfo.compress_size

Size of the compressed data.

ZipInfo.file_size

Size of the uncompressed file.

命令行界面

The zipfile module provides a simple command-line interface to interact with ZIP archives.

If you want to create a new ZIP archive, specify its name after the -c option and then list the filename(s) that should be included:

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

Passing a directory is also acceptable:

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

If you want to extract a ZIP archive into the specified directory, use the -e option:

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

For a list of the files in a ZIP archive, use the -l option:

$ python -m zipfile -l monty.zip

命令行选项

-l <zipfile>
--list <zipfile>

List files in a zipfile.

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

Create zipfile from source files.

-e <zipfile> <output_dir>
--extract <zipfile> <output_dir>

Extract zipfile into target directory.

-t <zipfile>
--test <zipfile>

Test whether the zipfile is valid or not.

Decompression pitfalls

The extraction in zipfile module might fail due to some pitfalls listed below.

From file itself

Decompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption.

File System limitations

Exceeding limitations on different file systems can cause decompression failed. Such as allowable characters in the directory entries, length of the file name, length of the pathname, size of a single file, and number of files, etc.

Resources limitations

The lack of memory or disk volume would lead to decompression failed. For example, decompression bombs (aka ZIP bomb) apply to zipfile library that can cause disk volume exhaustion.

Interruption

Interruption during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive.

Default behaviors of extraction

Not knowing the default extraction behaviors can cause unexpected decompression results. For example, when extracting the same archive twice, it overwrites files without asking.