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

13.5.1. ZipFile Objects

classzipfile.ZipFile(file,mode='r',compression=ZIP_STORED,allowZip64=True)

Open a ZIP file, wherefile can be either a path to a file (a string) or afile-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 causeRuntimeError to be raised. IfZIP_DEFLATED,ZIP_BZIP2 orZIP_LZMA is specified but the corresponding module(zlib,bz2 orlzma) is not available,RuntimeErroris also raised. The default isZIP_STORED. IfallowZip64 isTrue (the default) zipfile will create ZIP files that use the ZIP64extensions when the zipfile is larger than 4 GiB. If it is falsezipfilewill raise an exception when the ZIP file would require ZIP64 extensions.

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.

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)

Extract a member from the archive as a file-like object (ZipExtFile).nameis the name of the file in the archive, or aZipInfo object. Themode parameter, if included, must be one of the following:'r' (thedefault),'U', or'rU'. Choosing'U' or'rU' will enableuniversal newlines support in the read-only object.pwd is thepassword used for encrypted files. Callingopen() on a closedZipFile will raise aRuntimeError.

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

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

Note

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

Note

Objects returned byopen() can operate independently of theZipFile.

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.

Deprecated since version 3.4, will be removed in version 3.6:The'U' or'rU' mode. Useio.TextIOWrapper for readingcompressed text files inuniversal newlines mode.

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

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.

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 closed ZipFile will raise aRuntimeError. 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.

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. Callingtestzip() on a closed ZipFile will raise aRuntimeError.

ZipFile.write(filename,arcname=None,compress_type=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.The archive must be open with mode'w','x' or'a' – callingwrite() on a ZipFile created with mode'r' will raise aRuntimeError. Callingwrite() on a closed ZipFile will raise aRuntimeError.

Note

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

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.

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

Write the stringdata to the archive;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' – callingwritestr() on a ZipFile created with mode'r' will raise aRuntimeError. Callingwritestr() on a closed ZipFile willraise aRuntimeError.

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

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.

The following data attributes are also available:

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 text associated with the ZIP file. If assigning a comment to aZipFile instance created with mode'w','x' or'a',this should be astring no longer than 65535 bytes. Comments longer than this will betruncated in the written archive whenclose() is called.

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

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.

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

Instances have the following attributes:

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:

IndexValue
0Year (>= 1980)
1Month (one-based)
2Day of month (one-based)
3Hours (zero-based)
4Minutes (zero-based)
5Seconds (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.

ZipInfo.extra

Expansion field data. ThePKZIP Application Note containssome comments on the internal structure of the data contained in this string.

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.

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

13.5.4.1. Command-line options

-l <zipfile>

List files in a zipfile.

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

Create zipfile from source files.

-e <zipfile> <output_dir>

Extract zipfile into target directory.

-t <zipfile>

Test whether the zipfile is valid or not.