zipfile — Work with ZIP archives

Source code:Lib/zipfile.py


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.

New in version 3.2.

exceptionzipfile.BadZipfile

Alias ofBadZipFile, for compatibility with older Python versions.

Deprecated since version 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 Objects for constructor details.

classzipfile.Path

A pathlib-compatible wrapper for zip files. See sectionPath Objects for details.

New in version 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 Objects.

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.

Changed in version 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.

New in version 3.3.

zipfile.ZIP_LZMA

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

New in version 3.3.

Note

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.

See also

PKZIP Application Note

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

Info-ZIP Home Page

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

ZipFile Objects

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

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.

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

New in version 3.2:Added the ability to useZipFile as a context manager.

Changed in version 3.3:Added support forbzip2 andlzma compression.

Changed in version 3.4:ZIP64 extensions are enabled by default.

Changed in version 3.5:Added support for writing to unseekable streams.Added support for the'x' mode.

Changed in version 3.6:Previously, a plainRuntimeError was raised for unrecognizedcompression values.

Changed in version 3.6.2:Thefile parameter accepts apath-like object.

Changed in version 3.7:Add thecompresslevel parameter.

New in version 3.8:Thestrict_timestamps keyword-only argument

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.

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.

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.

Note

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.

Changed in version 3.6:Removed support ofmode='U'. Useio.TextIOWrapper for readingcompressed text files inuniversal newlines mode.

Changed in version 3.6:ZipFile.open() can now be used to write files into the archive with themode='w' option.

Changed in version 3.6:Callingopen() on a closed ZipFile will raise aValueError.Previously, aRuntimeError was raised.

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.

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

Note

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

Changed in version 3.6:Callingextract() on a closed ZipFile will raise aValueError. Previously, aRuntimeError was raised.

Changed in version 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.

Warning

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.

Changed in version 3.6:Callingextractall() on a closed ZipFile will raise aValueError. Previously, aRuntimeError was raised.

Changed in version 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 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 and, if specified,it will override 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.

Changed in version 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.

Changed in version 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'.

Note

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

Note

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

Note

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

Changed in version 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.

Note

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.

Changed in version 3.2:Thecompress_type argument.

Changed in version 3.6:Callingwritestr() on a ZipFile created with mode'r' ora closed ZipFile will raise aValueError. Previously,aRuntimeError 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 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.

Path objects expose the following features ofpathlib.Pathobjects:

Path objects are traversable using the/ operator.

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

Changed in version 3.9:Added support for text and binary modes for open. Defaultmode is now text.

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

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

Path.read_text(*,**)

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

Path.read_bytes()

Read the current file as bytes.

PyZipFile Objects

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)

New in version 3.2:Theoptimize parameter.

Changed in version 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

New in version 3.4:Thefilterfunc parameter.

Changed in version 3.6.2:Thepathname parameter accepts apath-like object.

Changed in version 3.7:Recursion sorts directory entries.

ZipInfo Objects

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.

New in version 3.6.

Changed in version 3.6.2:Thefilename parameter accepts apath-like object.

New in version 3.8:Thestrict_timestamps keyword-only argument

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

New in version 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)

Note

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.

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.