# 12.4. zipfile — 使用ZIP存档¶

1.6 新版功能.

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

class zipfile.ZipFile

class zipfile.PyZipFile

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

zipfile.is_zipfile(filename)

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 主页

## 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).

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.

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()

ZipFile.getinfo(name)

ZipFile.infolist()

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

ZipFile.extractall([path[, members[, 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.6 新版功能.

ZipFile.printdir()

ZipFile.setpassword(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.

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.

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).

ZipFile.debug

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

2

3

4

5

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

ZipInfo.create_version

ZipInfo.extract_version

ZipInfo.reserved

ZipInfo.flag_bits

ZIP 标志位。

ZipInfo.volume

ZipInfo.internal_attr

ZipInfo.external_attr

ZipInfo.header_offset

ZipInfo.CRC

ZipInfo.compress_size

ZipInfo.file_size

## 12.4.4. 命令行界面¶

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

$python -m zipfile -c monty.zip spam.txt eggs.txt  传入一个字典也是可接受的: $ python -m zipfile -c monty.zip life-of-brian_1979/


$python -m zipfile -e monty.zip target-dir/  对于一个 ZIP 归档中的文件列表，请使用 -l 选项: $ python -m zipfile -l monty.zip


### 12.4.4.1. 命令行选项¶

-l <zipfile>

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

-e <zipfile> <output_dir>

-t <zipfile>