zipfile --- 處理 ZIP 封存檔案

原始碼:Lib/zipfile/


The ZIP file format is a common archive and compression standard. This moduleprovides tools to create, read, write, append, and list a ZIP file. Anyadvanced use of this module will require an understanding of the format, asdefined inPKZIP Application Note.

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 GiB in size). It supportsdecryption of encrypted files in ZIP archives, but it currently cannotcreate an encrypted file. Decryption is extremely slow as it isimplemented in native Python rather than C.

The module defines the following items:

exceptionzipfile.BadZipFile

The error raised for bad ZIP files.

在 3.2 版被加入.

exceptionzipfile.BadZipfile

Alias ofBadZipFile, for compatibility with older Python versions.

在 3.2 版之後被棄用.

exceptionzipfile.LargeZipFile

The error raised when a ZIP file would require ZIP64 functionality but that hasnot been enabled.

classzipfile.ZipFile

The class for reading and writing ZIP files. See sectionZipFile 物件 for constructor details.

classzipfile.Path

Class that implements a subset of the interface provided bypathlib.Path, including the fullimportlib.resources.abc.Traversable interface.

在 3.8 版被加入.

classzipfile.PyZipFile

Class for creating ZIP archives containing Python libraries.

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

Class used to represent information about a member of an archive. Instancesof this class are returned by thegetinfo() andinfolist()methods ofZipFile objects. Most users of thezipfile modulewill not need to create these, but only use those created by thismodule.filename should be the full name of the archive member, anddate_time should be a tuple containing six fields which describe the timeof the last modification to the file; the fields are described in sectionZipInfo 物件.

在 3.13 版的變更:A publiccompress_level attribute has been added to expose theformerly protected_compresslevel. The older protected namecontinues to work as a property for backwards compatibility.

zipfile.is_zipfile(filename)

ReturnsTrue iffilename is a valid ZIP file based on its magic number,otherwise returnsFalse.filename may be a file or file-like object too.

在 3.1 版的變更:Support for file and file-like objects.

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 thezlib module.

zipfile.ZIP_BZIP2

The numeric constant for the BZIP2 compression method. This requires thebz2 module.

在 3.3 版被加入.

zipfile.ZIP_LZMA

The numeric constant for the LZMA compression method. This requires thelzma module.

在 3.3 版被加入.

備註

The ZIP file format specification has included support for bzip2 compressionsince 2001, and for LZMA compression since 2006. However, some tools(including older Python releases) do not support these compressionmethods, and may either refuse to process the ZIP file altogether,or fail to extract individual files.

也參考

PKZIP Application Note

Documentation on the ZIP file format by Phil Katz, the creator of the format andalgorithms used.

Info-ZIP 首頁

Information about the Info-ZIP project's ZIP archive programs and developmentlibraries.

ZipFile 物件

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

Open a ZIP file, wherefile can be a path to a file (a string), afile-like object or apath-like object.

Themode parameter should be'r' to read an existingfile,'w' to truncate and write a new file,'a' to append to anexisting file, or'x' to exclusively create and write a new file.Ifmode is'x' andfile refers to an existing file,aFileExistsError will be raised.Ifmode is'a' andfile refers to an existing ZIPfile, then additional files are added to it. Iffile does not refer to aZIP file, then a new ZIP archive is appended to the file. This is meant foradding a ZIP archive to another file (such aspython.exe). Ifmode is'a' and the file does not exist at all, it is created.Ifmode is'r' or'a', the file should be seekable.

compression is the ZIP compression method to use when writing the archive,and should beZIP_STORED,ZIP_DEFLATED,ZIP_BZIP2 orZIP_LZMA; unrecognizedvalues will causeNotImplementedError to be raised. IfZIP_DEFLATED,ZIP_BZIP2 orZIP_LZMA is specifiedbut the corresponding module (zlib,bz2 orlzma) is notavailable,RuntimeError is raised. The default isZIP_STORED.

IfallowZip64 isTrue (the default) zipfile will create ZIP files thatuse the ZIP64 extensions when the zipfile is larger than 4 GiB. If it isfalsezipfile will raise an exception when the ZIP file wouldrequire ZIP64 extensions.

Thecompresslevel parameter controls the compression level to use whenwriting files to the archive.When usingZIP_STORED orZIP_LZMA it has no effect.When usingZIP_DEFLATED integers0 through9 are accepted(seezlib for more information).When usingZIP_BZIP2 integers1 through9 are accepted(seebz2 for more information).

Thestrict_timestamps argument, when set toFalse, allows tozip files older than 1980-01-01 at the cost of setting thetimestamp to 1980-01-01.Similar behavior occurs with files newer than 2107-12-31,the timestamp is also set to the limit.

When mode is'r',metadata_encoding may be set to the name of a codec,which will be used to decode metadata such as the names of members and ZIPcomments.

If the file is created with mode'w','x' or'a' and thenclosed without adding any files to the archive, the appropriateZIP structures for an empty archive will be written to the file.

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

withZipFile('spam.zip','w')asmyzip:myzip.write('eggs.txt')

備註

metadata_encoding is an instance-wide setting for the ZipFile.It is not currently possible to set this on a per-member basis.

This attribute is a workaround for legacy implementations which producearchives with names in the current locale encoding or code page (mostlyon Windows). According to the .ZIP standard, the encoding of metadatamay be specified to be either IBM code page (default) or UTF-8 by a flagin the archive header.That flag takes precedence overmetadata_encoding, which isa Python-specific extension.

在 3.2 版的變更:新增ZipFile 作為情境管理器使用的能力。

在 3.3 版的變更:新增對於bzip2lzma 壓縮的支援。

在 3.4 版的變更:ZIP64 extensions are enabled by default.

在 3.5 版的變更:Added support for writing to unseekable streams.Added support for the'x' mode.

在 3.6 版的變更:Previously, a plainRuntimeError was raised for unrecognizedcompression values.

在 3.6.2 版的變更:file 參數接受一個path-like object

在 3.7 版的變更:新增compresslevel 參數。

在 3.8 版的變更:strict_timestamps 僅限關鍵字參數。

在 3.11 版的變更:Added support for specifying member name encoding for readingmetadata in the zipfile's directory and file headers.

ZipFile.close()

Close the archive file. You must callclose() before exiting your programor essential records will not be written.

ZipFile.getinfo(name)

Return aZipInfo object with information about the archive membername. Callinggetinfo() for a name not currently contained in thearchive will raise aKeyError.

ZipFile.infolist()

Return a list containing aZipInfo object for each member of thearchive. The objects are in the same order as their entries in the actual ZIPfile on disk if an existing archive was opened.

ZipFile.namelist()

Return a list of archive members by name.

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

Access a member of the archive as a binary file-like object.namecan be either the name of a file within the archive or aZipInfoobject. Themode parameter, if included, must be'r' (the default)or'w'.pwd is the password used to decrypt encrypted ZIP files as abytes object.

open() is also a context manager and therefore supports thewith statement:

withZipFile('spam.zip')asmyzip:withmyzip.open('eggs.txt')asmyfile:print(myfile.read())

Withmode'r' the file-like object(ZipExtFile) is read-only and provides the following methods:read(),readline(),readlines(),seek(),tell(),__iter__(),__next__().These objects can operate independently of the ZipFile.

Withmode='w', a writable file handle is returned, which supports thewrite() method. While a writable file handle is open,attempting to read or write other files in the ZIP file will raise aValueError.

In both cases the file-like object has also attributesname,which is equivalent to the name of a file within the archive, andmode, which is'rb' or'wb' depending on the input mode.

When writing a file, if the file size is not known in advance but may exceed2 GiB, passforce_zip64=True to ensure that the header format iscapable of supporting large files. If the file size is known in advance,construct aZipInfo object withfile_size set, anduse that as thename parameter.

備註

Theopen(),read() andextract() methods can take a filenameor aZipInfo object. You will appreciate this when trying to read aZIP file that contains members with duplicate names.

在 3.6 版的變更:Removed support ofmode='U'. Useio.TextIOWrapper for readingcompressed text files inuniversal newlines mode.

在 3.6 版的變更:ZipFile.open() can now be used to write files into the archive with themode='w' option.

在 3.6 版的變更:Callingopen() on a closed ZipFile will raise aValueError.Previously, aRuntimeError was raised.

在 3.13 版的變更:Added attributesname andmode for the writeablefile-like object.The value of themode attribute for the readable file-likeobject was changed from'r' to'rb'.

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

Extract a member from the archive to the current working directory;membermust be its full name or aZipInfo object. Its file information isextracted as accurately as possible.path specifies a different directoryto extract to.member can be a filename or aZipInfo object.pwd is the password used for encrypted files as abytes object.

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

備註

If a member filename is an absolute path, a drive/UNC sharepoint andleading (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 illegalcharacters (:,<,>,|,",?, and*)replaced by underscore (_).

在 3.6 版的變更:Callingextract() on a closed ZipFile will raise aValueError. Previously, aRuntimeError was raised.

在 3.6.2 版的變更:Thepath parameter accepts apath-like object.

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

Extract all members from the archive to the current working directory.pathspecifies a different directory to extract to.members is optional and mustbe a subset of the list returned bynamelist().pwd is the passwordused for encrypted files as abytes object.

警告

Never extract archives from untrusted sources without prior inspection.It is possible that files are created outside ofpath, e.g. membersthat have absolute filenames starting with"/" or filenames with twodots"..". This module attempts to prevent that.Seeextract() note.

在 3.6 版的變更:Callingextractall() on a closed ZipFile will raise aValueError. Previously, aRuntimeError was raised.

在 3.6.2 版的變更:Thepath parameter accepts apath-like object.

ZipFile.printdir()

Print a table of contents for the archive tosys.stdout.

ZipFile.setpassword(pwd)

Setpwd (abytes object) as default password to extract encrypted files.

ZipFile.read(name,pwd=None)

Return the bytes of the filename in the archive.name is the name of thefile in the archive, or aZipInfo object. The archive must be open forread or append.pwd is the password used for encrypted files as abytesobject and, if specified, overrides the default password set withsetpassword().Callingread() on a ZipFile that uses a compression method other thanZIP_STORED,ZIP_DEFLATED,ZIP_BZIP2 orZIP_LZMA will raise aNotImplementedError. An error will alsobe raised if the corresponding compression module is not available.

在 3.6 版的變更:Callingread() on a closed ZipFile will raise aValueError.Previously, aRuntimeError was raised.

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

在 3.6 版的變更:Callingtestzip() on a closed ZipFile will raise aValueError. Previously, aRuntimeError was raised.

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

Write the file namedfilename to the archive, giving it the archive namearcname (by default, this will be the same asfilename, but without a driveletter and with leading path separators removed). If given,compress_typeoverrides the value given for thecompression parameter to the constructor forthe new entry. Similarly,compresslevel will override the constructor ifgiven.The archive must be open with mode'w','x' or'a'.

備註

The ZIP file standard historically did not specify a metadata encoding,but strongly recommended CP437 (the original IBM PC encoding) forinteroperability. Recent versions allow use of UTF-8 (only). In thismodule, UTF-8 will automatically be used to write the member names ifthey contain any non-ASCII characters. It is not possible to writemember names in any encoding other than ASCII or UTF-8.

備註

Archive names should be relative to the archive root, that is, they should notstart with a path separator.

備註

Ifarcname (orfilename, ifarcname is not given) contains a nullbyte, the name of the file in the archive will be truncated at the null byte.

備註

A leading slash in the filename may lead to the archive being impossible toopen in some zip programs on Windows systems.

在 3.6 版的變更:Callingwrite() on a ZipFile created with mode'r' ora closed ZipFile will raise aValueError. Previously,aRuntimeError was raised.

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

Write a file into the archive. The contents isdata, which may be eitherastr or abytes instance; if it is astr,it is encoded as UTF-8 first.zinfo_or_arcname is either the filename it will be given in the archive, or aZipInfo instance. If it'san instance, at least the filename, date, and time must be given. If it's aname, 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 thecompressionparameter to the constructor for the new entry, or in thezinfo_or_arcname(if that is aZipInfo instance). Similarly,compresslevel willoverride the constructor if given.

備註

When passing aZipInfo instance as thezinfo_or_arcname parameter,the compression method used will be that specified in thecompress_typemember of the givenZipInfo instance. By default, theZipInfo constructor sets this member toZIP_STORED.

在 3.2 版的變更:compress_type 引數。

在 3.6 版的變更:Callingwritestr() on a ZipFile created with mode'r' ora closed ZipFile will raise aValueError. Previously,aRuntimeError was raised.

ZipFile.mkdir(zinfo_or_directory,mode=511)

Create a directory inside the archive. Ifzinfo_or_directory is a string,a directory is created inside the archive with the mode that is specified inthemode argument. If, however,zinfo_or_directory isaZipInfo instance then themode argument is ignored.

The archive must be opened with mode'w','x' or'a'.

在 3.11 版被加入.

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 from0 (the default, nooutput) to3 (the most output). Debugging information is written tosys.stdout.

ZipFile.comment

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

Path Objects

classzipfile.Path(root,at='')

Construct a Path object from aroot zipfile (which may be aZipFile instance orfile suitable for passing totheZipFile 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.

備註

ThePath class does not sanitize filenames within the ZIP archive. UnliketheZipFile.extract() andZipFile.extractall() methods, it is thecaller's responsibility to validate or sanitize filenames to prevent path traversalvulnerabilities (e.g., filenames containing ".." or absolute paths). When handlinguntrusted archives, consider resolving filenames usingos.path.abspath()and checking against the target directory withos.path.commonpath().

Path objects expose the following features ofpathlib.Pathobjects:

Path objects are traversable using the/ operator orjoinpath.

Path.name

The final path component.

Path.open(mode='r',*,pwd,**)

InvokeZipFile.open() on the current path.Allows opening for read or write, text or binarythrough supported modes: 'r', 'w', 'rb', 'wb'.Positional and keyword arguments are passed through toio.TextIOWrapper when opened as text andignored otherwise.pwd is thepwd parameter toZipFile.open().

在 3.9 版的變更:Added support for text and binary modes for open. Defaultmode is now text.

在 3.11.2 版的變更:Theencoding parameter can be supplied as a positional argumentwithout causing aTypeError. As it could in 3.9. Code needing tobe compatible with unpatched 3.10 and 3.11 versions must pass allio.TextIOWrapper arguments,encoding included, as keywords.

Path.iterdir()

Enumerate the children of the current directory.

Path.is_dir()

ReturnTrue if the current context references a directory.

Path.is_file()

ReturnTrue if the current context references a file.

Path.is_symlink()

ReturnTrue if the current context references a symbolic link.

在 3.12 版被加入.

在 3.13 版的變更:Previously,is_symlink would unconditionally returnFalse.

Path.exists()

ReturnTrue if the current context references a file ordirectory in the zip file.

Path.suffix

The last dot-separated portion of the final component, if any.This is commonly called the file extension.

在 3.11 版被加入:新增Path.suffix 特性。

Path.stem

The final path component, without its suffix.

在 3.11 版被加入:新增Path.stem 特性。

Path.suffixes

A list of the path’s suffixes, commonly called file extensions.

在 3.11 版被加入:新增Path.suffixes 特性。

Path.read_text(*,**)

Read the current file as unicode text. Positional andkeyword arguments are passed through toio.TextIOWrapper (exceptbuffer, which isimplied by the context).

在 3.11.2 版的變更:Theencoding parameter can be supplied as a positional argumentwithout causing aTypeError. As it could in 3.9. Code needing tobe compatible with unpatched 3.10 and 3.11 versions must pass allio.TextIOWrapper arguments,encoding included, as keywords.

Path.read_bytes()

Read the current file as bytes.

Path.joinpath(*other)

Return a new Path object with each of theother argumentsjoined. The following are equivalent:

>>>Path(...).joinpath('child').joinpath('grandchild')>>>Path(...).joinpath('child','grandchild')>>>Path(...)/'child'/'grandchild'

在 3.10 版的變更:Prior to 3.10,joinpath was undocumented and acceptedexactly one parameter.

Thezipp project provides backportsof the latest path object functionality to older Pythons. Usezipp.Path in place ofzipfile.Path for early access tochanges.

PyZipFile 物件

ThePyZipFile constructor takes the same parameters as theZipFile constructor, and one additional parameter,optimize.

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

在 3.2 版的變更:新增optimize 參數。

在 3.4 版的變更:ZIP64 extensions are enabled by default.

Instances have one method in addition to those ofZipFile objects:

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

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

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

If theoptimize parameter toPyZipFile was0,1 or2, only files with that optimization level (seecompile()) areadded to the archive, compiling if necessary.

Ifpathname is a file, the filename must end with.py, andjust the (corresponding*.pyc) file is added at the top level(no path information). Ifpathname is a file that does not end with.py, aRuntimeError 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 apackage directory, then all*.pyc are added under the packagename 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 stringargument. It will be passed each path (including each individual fullfile path) before it is added to the archive. Iffilterfunc returns afalse value, the path will not be added, and if it is a directory itscontents will be ignored. For example, if our test files are all eitherintest directories or start with the stringtest_, we can use afilterfunc to exclude them:

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

Thewritepy() method makes archives with file names likethis:

string.pyc# Top level nametest/__init__.pyc# Package directorytest/testall.pyc# Module test.testalltest/bogus/__init__.pyc# Subpackage directorytest/bogus/myfile.pyc# Submodule test.bogus.myfile

在 3.4 版的變更:新增filterfunc 參數。

在 3.6.2 版的變更:Thepathname parameter accepts apath-like object.

在 3.7 版的變更:Recursion sorts directory entries.

ZipInfo 物件

Instances of theZipInfo class are returned by thegetinfo() andinfolist() methods ofZipFile objects. Each object storesinformation about a single member of the ZIP archive.

There is one classmethod to make aZipInfo instance for a filesystemfile:

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

Construct aZipInfo instance for a file on the filesystem, inpreparation for adding it to a zip file.

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

Ifarcname is specified, it is used as the name within the archive.Ifarcname is not specified, the name will be the same asfilename, butwith any drive letter and leading path separators removed.

Thestrict_timestamps argument, when set toFalse, allows tozip files older than 1980-01-01 at the cost of setting thetimestamp to 1980-01-01.Similar behavior occurs with files newer than 2107-12-31,the timestamp is also set to the limit.

在 3.6 版被加入.

在 3.6.2 版的變更:Thefilename parameter accepts apath-like object.

在 3.8 版的變更:新增strict_timestamps 僅限關鍵字參數。

Instances have the following methods and attributes:

ZipInfo.is_dir()

ReturnTrue 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

The time and date of the last modification to the archive member. This is atuple of six values:

Index

Value

0

Year (>= 1980)

1

Month (one-based)

2

Day of month (one-based)

3

Hours (zero-based)

4

Minutes (zero-based)

5

Seconds (zero-based)

備註

The ZIP file format does not support timestamps before 1980.

ZipInfo.compress_type

Type of compression for the archive member.

ZipInfo.comment

Comment for the individual archive member as abytes object.

ZipInfo.extra

Expansion field data. ThePKZIP Application Note containssome comments on the internal structure of the data contained in thisbytes 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

Must be zero.

ZipInfo.flag_bits

ZIP flag bits.

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.

Command-Line Interface

Thezipfile module provides a simple command-line interface to interactwith ZIP archives.

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

$python-mzipfile-cmonty.zipspam.txteggs.txt

Passing a directory is also acceptable:

$python-mzipfile-cmonty.ziplife-of-brian_1979/

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

$python-mzipfile-emonty.ziptarget-dir/

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

$python-mzipfile-lmonty.zip

Command-line options

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

--metadata-encoding<encoding>

Specify encoding of member names for-l,-e and-t.

在 3.11 版被加入.

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 orunsupported 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 decompressionfailed. For example, decompression bombs (akaZIP bomb)apply to zipfile library that can cause disk volume exhaustion.

Interruption

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

Default behaviors of extraction

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