Source code: Lib/xmlrpc/server.py
The xmlrpc.server module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.
Warning
The xmlrpc.server module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.
Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The requestHandler parameter should be a factory for request handler instances; it defaults to SimpleXMLRPCRequestHandler. The addr and requestHandler parameters are passed to the socketserver.TCPServer constructor. If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The bind_and_activate parameter controls whether server_bind() and server_activate() are called immediately by the constructor; it defaults to true. Setting it to false allows code to manipulate the allow_reuse_address class variable before the address is bound. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.
Changed in version 3.3: The use_builtin_types flag was added.
Create a new instance to handle XML-RPC requests in a CGI environment. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.
Changed in version 3.3: The use_builtin_types flag was added.
Create a new request handler instance. This request handler supports POST requests and modifies logging so that the logRequests parameter to the SimpleXMLRPCServer constructor parameter is honored.
The SimpleXMLRPCServer class is based on socketserver.TCPServer and provides a means of creating simple, stand alone XML-RPC servers.
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character.
This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used.
Changed in version 3.7: register_function() can be used as a decorator.
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request. Its API is def _dispatch(self, method, params) (note that params does not represent a variable argument list). If it calls an underlying function to perform its task, that function is called as func(*params), expanding the parameter list. The return value from _dispatch() is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method.
If the optional allow_dotted_names argument is true and the instance does not have a _dispatch() method, then if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.
Warning
Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.
Registers the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.
Registers the XML-RPC multicall function system.multicall.
An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a 404 “no such page” HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ('/', '/RPC2').
Server code:
The following client code will call the methods made available by the preceding server:
register_function() can also be used as a decorator. The previous server example can register functions in a decorator way:
The following example included in the Lib/xmlrpc/server.py module shows a server allowing dotted names and registering a multicall function.
Warning
Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this example only within a secure, closed network.
This ExampleService demo can be invoked from the command line:
The client that interacts with the above server is included in Lib/xmlrpc/client.py:
This client which interacts with the demo XMLRPC server can be invoked as:
The CGIXMLRPCRequestHandler class can be used to handle XML-RPC requests sent to Python CGI scripts.
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character.
This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used.
Changed in version 3.7: register_function() can be used as a decorator.
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request; the return value is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method; if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.
Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.
Register the XML-RPC multicall function system.multicall.
Handle an XML-RPC request. If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used.
Example:
These classes extend the above classes to serve HTML documentation in response to HTTP GET requests. Servers can either be free standing, using DocXMLRPCServer, or embedded in a CGI environment, using DocCGIXMLRPCRequestHandler.
Create a new server instance. All parameters have the same meaning as for SimpleXMLRPCServer; requestHandler defaults to DocXMLRPCRequestHandler.
Changed in version 3.3: The use_builtin_types flag was added.
Create a new instance to handle XML-RPC requests in a CGI environment.
Create a new request handler instance. This request handler supports XML-RPC POST requests, documentation GET requests, and modifies logging so that the logRequests parameter to the DocXMLRPCServer constructor parameter is honored.
The DocXMLRPCServer class is derived from SimpleXMLRPCServer and provides a means of creating self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.
The DocCGIXMLRPCRequestHandler class is derived from CGIXMLRPCRequestHandler and provides a means of creating self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.


Create a new instance to handle XML-RPC requests in a CGI environment. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.
Changed in version 3.3: The use_builtin_types flag was added.


Handle an XML-RPC request. If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used.


Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character.
This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used.
Changed in version 3.7: register_function() can be used as a decorator.


Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request; the return value is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method; if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.


Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.


Register the XML-RPC multicall function system.multicall.


Create a new instance to handle XML-RPC requests in a CGI environment.


Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.


Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.


Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.


Create a new request handler instance. This request handler supports XML-RPC POST requests, documentation GET requests, and modifies logging so that the logRequests parameter to the DocXMLRPCServer constructor parameter is honored.


Create a new server instance. All parameters have the same meaning as for SimpleXMLRPCServer; requestHandler defaults to DocXMLRPCRequestHandler.
Changed in version 3.3: The use_builtin_types flag was added.


Create a new request handler instance. This request handler supports POST requests and modifies logging so that the logRequests parameter to the SimpleXMLRPCServer constructor parameter is honored.


An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a 404 “no such page” HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ('/', '/RPC2').


Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The requestHandler parameter should be a factory for request handler instances; it defaults to SimpleXMLRPCRequestHandler. The addr and requestHandler parameters are passed to the socketserver.TCPServer constructor. If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The bind_and_activate parameter controls whether server_bind() and server_activate() are called immediately by the constructor; it defaults to true. Setting it to false allows code to manipulate the allow_reuse_address class variable before the address is bound. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.
Changed in version 3.3: The use_builtin_types flag was added.


Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request. Its API is def _dispatch(self, method, params) (note that params does not represent a variable argument list). If it calls an underlying function to perform its task, that function is called as func(*params), expanding the parameter list. The return value from _dispatch() is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method.
If the optional allow_dotted_names argument is true and the instance does not have a _dispatch() method, then if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.
Warning
Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.


Registers the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.


Registers the XML-RPC multicall function system.multicall.


Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.


Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.
zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.
zip() in conjunction with the * operator can be used to unzip a list:


New in version 3.5.
Source code: Lib/zipapp.py
This module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API.
The following example shows how the Command-Line Interface can be used to create an executable archive from a directory containing Python code. When run, the archive will execute the main function from the module myapp in the archive.
When called as a program from the command line, the following form is used:
If source is a directory, this will create an archive from the contents of source. If source is a file, it should be an archive, and it will be copied to the target archive (or the contents of its shebang line will be displayed if the –info option is specified).
The following options are understood:
Write the output to a file named output. If this option is not specified, the output filename will be the same as the input source, with the extension .pyz added. If an explicit filename is given, it is used as is (so a .pyz extension should be included if required).
An output filename must be specified if the source is an archive (and in that case, output must not be the same as source).
Add a #! line to the archive specifying interpreter as the command to run. Also, on POSIX, make the archive executable. The default is to write no #! line, and not make the file executable.
Write a __main__.py file to the archive that executes mainfn. The mainfn argument should have the form “pkg.mod:fn”, where “pkg.mod” is a package/module in the archive, and “fn” is a callable in the given module. The __main__.py file will execute that callable.
--main cannot be specified when copying an archive.
Compress files with the deflate method, reducing the size of the output file. By default, files are stored uncompressed in the archive.
--compress has no effect when copying an archive.
New in version 3.7.
Display the interpreter embedded in the archive, for diagnostic purposes. In this case, any other options are ignored and SOURCE must be an archive, not a directory.
Print a short usage message and exit.
The module defines two convenience functions:
Create an application archive from source. The source can be any of the following:
The target argument determines where the resulting archive will be written:
The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSIX, this will be interpreted by the OS, and on Windows it will be handled by the Python launcher. Omitting the interpreter results in no shebang line being written. If an interpreter is specified, and the target is a filename, the executable bit of the target file will be set.
The main argument specifies the name of a callable which will be used as the main program for the archive. It can only be specified if the source is a directory, and the source does not already contain a __main__.py file. The main argument should take the form “pkg.module:callable” and the archive will be run by importing “pkg.module” and executing the given callable with no arguments. It is an error to omit main if the source is a directory and does not contain a __main__.py file, as otherwise the resulting archive would not be executable.
The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return True if the file is to be added.
The optional compressed argument determines whether files are compressed. If set to True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive.
If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive.
When copying an existing archive, file objects supplied only need read and readline, or write methods. When creating an archive from a directory, if the target is a file object it will be passed to the zipfile.ZipFile class, and must supply the methods needed by that class.
New in version 3.7: Added the filter and compressed arguments.
Return the interpreter specified in the #! line at the start of the archive. If there is no #! line, return None. The archive argument can be a filename or a file-like object open for reading in bytes mode. It is assumed to be at the start of the archive.
Pack up a directory into an archive, and run it.
The same can be done using the create_archive() function:
To make the application directly executable on POSIX, specify an interpreter to use.
To replace the shebang line on an existing archive, create a modified archive using the create_archive() function:
To update the file in place, do the replacement in memory using a BytesIO object, and then overwrite the source afterwards. Note that there is a risk when overwriting a file in place that an error will result in the loss of the original file. This code does not protect against such errors, but production code should do so. Also, this method will only work if the archive fits in memory:
Note that if you specify an interpreter and then distribute your application archive, you need to ensure that the interpreter used is portable. The Python launcher for Windows supports most common forms of POSIX #! line, but there are other issues to consider:
Typically, you should use an “/usr/bin/env python2” or “/usr/bin/env python3”, depending on whether your code is written for Python 2 or 3.
Using the zipapp module, it is possible to create self-contained Python programs, which can be distributed to end users who only need to have a suitable version of Python installed on their system. The key to doing this is to bundle all of the application’s dependencies into the archive, along with the application code.
The steps to create a standalone archive are as follows:
Install all of your application’s dependencies into the myapp directory, using pip:
(this assumes you have your project requirements in a requirements.txt file - if not, you can just list the dependencies manually on the pip command line).
Package the application using:
This will produce a standalone executable, which can be run on any machine with the appropriate interpreter available. See Specifying the Interpreter for details. It can be shipped to users as a single file.
On Unix, the myapp.pyz file is executable as it stands. You can rename the file to remove the .pyz extension if you prefer a “plain” command name. On Windows, the myapp.pyz[w] file is executable by virtue of the fact that the Python interpreter registers the .pyz and .pyzw file extensions when installed.
On Windows, registration of the .pyz extension is optional, and furthermore, there are certain places that don’t recognise registered extensions “transparently” (the simplest example is that subprocess.run(['myapp']) won’t find your application - you need to explicitly specify the extension).
On Windows, therefore, it is often preferable to create an executable from the zipapp. This is relatively easy, although it does require a C compiler. The basic approach relies on the fact that zipfiles can have arbitrary data prepended, and Windows exe files can have arbitrary data appended. So by creating a suitable launcher and tacking the .pyz file onto the end of it, you end up with a single-file executable that runs your application.
A suitable launcher can be as simple as the following:
If you define the WINDOWS preprocessor symbol, this will generate a GUI executable, and without it, a console executable.
To compile the executable, you can either just use the standard MSVC command line tools, or you can take advantage of the fact that distutils knows how to compile Python source:
The resulting launcher uses the “Limited ABI”, so it will run unchanged with any version of Python 3.x. All it needs is for Python (python3.dll) to be on the user’s PATH.
For a fully standalone distribution, you can distribute the launcher with your application appended, bundled with the Python “embedded” distribution. This will run on any PC with the appropriate architecture (32 bit or 64 bit).
There are some limitations to the process of bundling your application into a single file. In most, if not all, cases they can be addressed without needing major changes to your application.
Python has been able to execute zip files which contain a __main__.py file since version 2.6. In order to be executed by Python, an application archive simply has to be a standard zip file containing a __main__.py file which will be run as the entry point for the application. As usual for any Python script, the parent of the script (in this case the zip file) will be placed on sys.path and thus further modules can be imported from the zip file.
The zip file format allows arbitrary data to be prepended to a zip file. The zip application format uses this ability to prepend a standard POSIX “shebang” line to the file (#!/path/to/interpreter).
Formally, the Python zip application format is therefore:
If an application archive has a shebang line, it may have the executable bit set on POSIX systems, to allow it to be executed directly.
There is no requirement that the tools in this module are used to create application archives - the module is a convenience, but archives in the above format created by any means are acceptable to Python.


Create an application archive from source. The source can be any of the following:
The target argument determines where the resulting archive will be written:
The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSIX, this will be interpreted by the OS, and on Windows it will be handled by the Python launcher. Omitting the interpreter results in no shebang line being written. If an interpreter is specified, and the target is a filename, the executable bit of the target file will be set.
The main argument specifies the name of a callable which will be used as the main program for the archive. It can only be specified if the source is a directory, and the source does not already contain a __main__.py file. The main argument should take the form “pkg.module:callable” and the archive will be run by importing “pkg.module” and executing the given callable with no arguments. It is an error to omit main if the source is a directory and does not contain a __main__.py file, as otherwise the resulting archive would not be executable.
The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return True if the file is to be added.
The optional compressed argument determines whether files are compressed. If set to True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive.
If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive.
When copying an existing archive, file objects supplied only need read and readline, or write methods. When creating an archive from a directory, if the target is a file object it will be passed to the zipfile.ZipFile class, and must supply the methods needed by that class.
New in version 3.7: Added the filter and compressed arguments.


Return the interpreter specified in the #! line at the start of the archive. If there is no #! line, return None. The archive argument can be a filename or a file-like object open for reading in bytes mode. It is assumed to be at the start of the archive.


Source code: Lib/zipfile.py
The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP 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 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.
The module defines the following items:
The error raised for bad ZIP files.
New in version 3.2.
Alias of BadZipFile, for compatibility with older Python versions.
Deprecated since version 3.2.
The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled.
The class for reading and writing ZIP files. See section ZipFile Objects for constructor details.
A pathlib-compatible wrapper for zip files. See section Path Objects for details.
New in version 3.8.
Class for creating ZIP archives containing Python libraries.
Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of ZipFile objects. Most users of the zipfile module will not need to create these, but only use those created by this module. filename should be the full name of the archive member, and date_time should be a tuple containing six fields which describe the time of the last modification to the file; the fields are described in section ZipInfo Objects.
Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too.
Changed in version 3.1: Support for file and file-like objects.
The numeric constant for an uncompressed archive member.
The numeric constant for the usual ZIP compression method. This requires the zlib module.
The numeric constant for the BZIP2 compression method. This requires the bz2 module.
New in version 3.3.
The numeric constant for the LZMA compression method. This requires the lzma module.
New in version 3.3.
Note
The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files.
See also
Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used.
Information about the Info-ZIP project’s ZIP archive programs and development libraries.
Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object.
The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised. 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). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable.
compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED.
If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions.
The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).
The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp 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 then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.
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:
New in version 3.2: Added the ability to use ZipFile as a context manager.
Changed in version 3.3: Added support for bzip2 and lzma 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 plain RuntimeError was raised for unrecognized compression values.
Changed in version 3.6.2: The file parameter accepts a path-like object.
Changed in version 3.7: Add the compresslevel parameter.
New in version 3.8: The strict_timestamps keyword-only argument
Close the archive file. You must call close() before exiting your program or essential records will not be written.
Return a ZipInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError.
Return a list containing a ZipInfo object for each member of the archive. The objects are in the same order as their entries in the actual ZIP file on disk if an existing archive was opened.
Return a list of archive members by name.
Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode 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 the with statement:
With mode '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.
With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError.
When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter.
Note
The open(), read() and extract() methods can take a filename or a ZipInfo object. You will appreciate this when trying to read a ZIP file that contains members with duplicate names.
Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.
Changed in version 3.6: open() can now be used to write files into the archive with the mode='w' option.
Changed in version 3.6: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
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.
Returns the normalized path created (a directory or new file).
Note
If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_).
Changed in version 3.6: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
Changed in version 3.6.2: The path parameter accepts a path-like object.
Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files.
Warning
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 "..". This module attempts to prevent that. See extract() note.
Changed in version 3.6: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
Changed in version 3.6.2: The path parameter accepts a path-like object.
Print a table of contents for the archive to sys.stdout.
Set pwd as default password to extract encrypted files.
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 ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available.
Changed in version 3.6: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
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.
Changed in version 3.6: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
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. Similarly, compresslevel will override the constructor if given. 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 not start with a path separator.
Note
If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte.
Changed in version 3.6: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
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.
Note
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.
Changed in version 3.2: The compress_type argument.
Changed in version 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:
Name of the ZIP file.
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.
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.
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.
The final path component.
Invoke ZipFile.open() on the current path. Allows opening for read or write, text or binary through supported modes: ‘r’, ‘w’, ‘rb’, ‘wb’. Positional and keyword arguments are passed through to io.TextIOWrapper when opened as text and ignored otherwise. pwd is the pwd parameter to ZipFile.open().
Changed in version 3.9: Added support for text and binary modes for open. Default mode is now text.
Enumerate the children of the current directory.
Return True if the current context references a directory.
Return True if the current context references a file.
Return True if the current context references a file or directory in the zip file.
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).
Read the current file as bytes.
The PyZipFile constructor takes the same parameters as the ZipFile constructor, and one additional parameter, optimize.
New in version 3.2: The optimize parameter.
Changed in version 3.4: ZIP64 extensions are enabled by default.
Instances have one method in addition to those of ZipFile objects:
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:
The writepy() method makes archives with file names like this:
New in version 3.4: The filterfunc parameter.
Changed in version 3.6.2: The pathname parameter accepts a path-like object.
Changed in version 3.7: Recursion sorts directory entries.
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:
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.
The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp 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: The filename parameter accepts a path-like object.
New in version 3.8: The strict_timestamps keyword-only argument
Instances have the following methods and attributes:
Return True if this archive member is a directory.
This uses the entry’s name: directories should always end with /.
New in version 3.6.
Name of the file in the archive.
The time and date of the last modification to the archive member. This is a tuple 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.
Type of compression for the archive member.
Comment for the individual archive member as a bytes object.
Expansion field data. The PKZIP Application Note contains some comments on the internal structure of the data contained in this bytes object.
System which created ZIP archive.
PKZIP version which created ZIP archive.
PKZIP version needed to extract archive.
Must be zero.
ZIP flag bits.
Volume number of file header.
Internal attributes.
External file attributes.
Byte offset to the file header.
CRC-32 of the uncompressed file.
Size of the compressed data.
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:
Passing a directory is also acceptable:
If you want to extract a ZIP archive into the specified directory, use the -e option:
For a list of the files in a ZIP archive, use the -l option:
List files in a zipfile.
Create zipfile from source files.
Extract zipfile into target directory.
Test whether the zipfile is valid or not.
The extraction in zipfile module might fail due to some pitfalls listed below.
Decompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption.
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.
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 during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive.
Not knowing the default extraction behaviors can cause unexpected decompression results. For example, when extracting the same archive twice, it overwrites files without asking.


Alias of BadZipFile, for compatibility with older Python versions.
Deprecated since version 3.2.


The error raised for bad ZIP files.
New in version 3.2.


Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too.
Changed in version 3.1: Support for file and file-like objects.


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


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.


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


Return True if the current context references a directory.


Return True if the current context references a file.


Enumerate the children of the current directory.


Invoke ZipFile.open() on the current path. Allows opening for read or write, text or binary through supported modes: ‘r’, ‘w’, ‘rb’, ‘wb’. Positional and keyword arguments are passed through to io.TextIOWrapper when opened as text and ignored otherwise. pwd is the pwd parameter to ZipFile.open().
Changed in version 3.9: Added support for text and binary modes for open. Default mode is now 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).


New in version 3.2: The optimize parameter.
Changed in version 3.4: ZIP64 extensions are enabled by default.
Instances have one method in addition to those of ZipFile objects:
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:
The writepy() method makes archives with file names like this:
New in version 3.4: The filterfunc parameter.
Changed in version 3.6.2: The pathname parameter accepts a path-like object.
Changed in version 3.7: Recursion sorts directory entries.


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:
The writepy() method makes archives with file names like this:
New in version 3.4: The filterfunc parameter.
Changed in version 3.6.2: The pathname parameter accepts a path-like object.
Changed in version 3.7: Recursion sorts directory entries.


Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object.
The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised. 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). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable.
compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED.
If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions.
The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).
The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp 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 then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.
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:
New in version 3.2: Added the ability to use ZipFile as a context manager.
Changed in version 3.3: Added support for bzip2 and lzma 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 plain RuntimeError was raised for unrecognized compression values.
Changed in version 3.6.2: The file parameter accepts a path-like object.
Changed in version 3.7: Add the compresslevel parameter.
New in version 3.8: The strict_timestamps keyword-only argument


Close the archive file. You must call close() before exiting your program or essential records will not be written.


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.


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.


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.
Returns the normalized path created (a directory or new file).
Note
If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_).
Changed in version 3.6: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
Changed in version 3.6.2: The path parameter accepts a path-like object.


Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files.
Warning
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 "..". This module attempts to prevent that. See extract() note.
Changed in version 3.6: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
Changed in version 3.6.2: The path parameter accepts a path-like object.


Return a ZipInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError.


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


Return a list of archive members by name.


Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode 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 the with statement:
With mode '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.
With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError.
When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter.
Note
The open(), read() and extract() methods can take a filename or a ZipInfo object. You will appreciate this when trying to read a ZIP file that contains members with duplicate names.
Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.
Changed in version 3.6: open() can now be used to write files into the archive with the mode='w' option.
Changed in version 3.6: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.


Print a table of contents for the archive to sys.stdout.


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 ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available.
Changed in version 3.6: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.


Set pwd as default password to extract encrypted files.


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.
Changed in version 3.6: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.


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. Similarly, compresslevel will override the constructor if given. 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 not start with a path separator.
Note
If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte.
Changed in version 3.6: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.


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.
Note
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.
Changed in version 3.2: The compress_type argument.
Changed in version 3.6: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.


Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of ZipFile objects. Most users of the zipfile module will not need to create these, but only use those created by this module. filename should be the full name of the archive member, and date_time should be a tuple containing six fields which describe the time of the last modification to the file; the fields are described in section ZipInfo Objects.


Comment for the individual archive member as a bytes object.


Type of compression for the archive member.


PKZIP version which created ZIP archive.


The time and date of the last modification to the archive member. This is a tuple 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.


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


PKZIP version needed to extract archive.


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.
The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp 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: The filename parameter accepts a path-like object.
New in version 3.8: The strict_timestamps keyword-only argument


Return True if this archive member is a directory.
This uses the entry’s name: directories should always end with /.
New in version 3.6.


The numeric constant for the BZIP2 compression method. This requires the bz2 module.
New in version 3.3.


The numeric constant for the usual ZIP compression method. This requires the zlib module.


The numeric constant for the LZMA compression method. This requires the lzma module.
New in version 3.3.
Note
The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files.


The numeric constant for an uncompressed archive member.


Source code: Lib/zipimport.py
This module adds the ability to import Python modules (*.py, *.pyc) and packages from ZIP-format archives. It is usually not needed to use the zipimport module explicitly; it is automatically used by the built-in import mechanism for sys.path items that are paths to ZIP archives.
Typically, sys.path is a list of directory names as strings. This module also allows an item of sys.path to be a string naming a ZIP file archive. The ZIP archive can contain a subdirectory structure to support package imports, and a path within the archive can be specified to only import from a subdirectory. For example, the path example.zip/lib/ would only import from the lib/ subdirectory within the archive.
Any files may be present in the ZIP archive, but only files .py and .pyc are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc file, meaning that if a ZIP archive doesn’t contain .pyc files, importing may be rather slow.
Changed in version 3.8: Previously, ZIP archives with an archive comment were not supported.
See also
Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used.
Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302.
The PEP to add the import hooks that help this module work.
This module defines an exception:
Exception raised by zipimporter objects. It’s a subclass of ImportError, so it can be caught as ImportError, too.
zipimporter is the class for importing ZIP files.
Create a new zipimporter instance. archivepath must be a path to a ZIP file, or to a specific path within a ZIP file. For example, an archivepath of foo/bar.zip/lib will look for modules in the lib directory inside the ZIP file foo/bar.zip (provided that it exists).
ZipImportError is raised if archivepath doesn’t point to a valid ZIP archive.
Search for a module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the zipimporter instance itself if the module was found, or None if it wasn’t. The optional path argument is ignored—it’s there for compatibility with the importer protocol.
Return the code object for the specified module. Raise ZipImportError if the module couldn’t be found.
Return the data associated with pathname. Raise OSError if the file wasn’t found.
Changed in version 3.3: IOError used to be raised instead of OSError.
Return the value __file__ would be set to if the specified module was imported. Raise ZipImportError if the module couldn’t be found.
New in version 3.1.
Return the source code for the specified module. Raise ZipImportError if the module couldn’t be found, return None if the archive does contain the module, but has no source for it.
Return True if the module specified by fullname is a package. Raise ZipImportError if the module couldn’t be found.
Load the module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the imported module, or raises ZipImportError if it wasn’t found.
The file name of the importer’s associated ZIP file, without a possible subpath.
The subpath within the ZIP file where modules are searched. This is the empty string for zipimporter objects which point to the root of the ZIP file.
The archive and prefix attributes, when combined with a slash, equal the original archivepath argument given to the zipimporter constructor.
Here is an example that imports a module from a ZIP archive - note that the zipimport module is not explicitly used.


Create a new zipimporter instance. archivepath must be a path to a ZIP file, or to a specific path within a ZIP file. For example, an archivepath of foo/bar.zip/lib will look for modules in the lib directory inside the ZIP file foo/bar.zip (provided that it exists).
ZipImportError is raised if archivepath doesn’t point to a valid ZIP archive.
Search for a module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the zipimporter instance itself if the module was found, or None if it wasn’t. The optional path argument is ignored—it’s there for compatibility with the importer protocol.
Return the code object for the specified module. Raise ZipImportError if the module couldn’t be found.
Return the data associated with pathname. Raise OSError if the file wasn’t found.
Changed in version 3.3: IOError used to be raised instead of OSError.
Return the value __file__ would be set to if the specified module was imported. Raise ZipImportError if the module couldn’t be found.
New in version 3.1.
Return the source code for the specified module. Raise ZipImportError if the module couldn’t be found, return None if the archive does contain the module, but has no source for it.
Return True if the module specified by fullname is a package. Raise ZipImportError if the module couldn’t be found.
Load the module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the imported module, or raises ZipImportError if it wasn’t found.
The file name of the importer’s associated ZIP file, without a possible subpath.
The subpath within the ZIP file where modules are searched. This is the empty string for zipimporter objects which point to the root of the ZIP file.
The archive and prefix attributes, when combined with a slash, equal the original archivepath argument given to the zipimporter constructor.


The file name of the importer’s associated ZIP file, without a possible subpath.


Search for a module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the zipimporter instance itself if the module was found, or None if it wasn’t. The optional path argument is ignored—it’s there for compatibility with the importer protocol.


Return the code object for the specified module. Raise ZipImportError if the module couldn’t be found.


Return the data associated with pathname. Raise OSError if the file wasn’t found.
Changed in version 3.3: IOError used to be raised instead of OSError.


Return the value __file__ would be set to if the specified module was imported. Raise ZipImportError if the module couldn’t be found.
New in version 3.1.


Return the source code for the specified module. Raise ZipImportError if the module couldn’t be found, return None if the archive does contain the module, but has no source for it.


Return True if the module specified by fullname is a package. Raise ZipImportError if the module couldn’t be found.


Load the module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the imported module, or raises ZipImportError if it wasn’t found.


The subpath within the ZIP file where modules are searched. This is the empty string for zipimporter objects which point to the root of the ZIP file.


Exception raised by zipimporter objects. It’s a subclass of ImportError, so it can be caught as ImportError, too.


For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. The zlib library has its own home page at https://www.zlib.net. There are known incompatibilities between the Python module and versions of the zlib library earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using 1.1.4 or later.
zlib’s functions have many options and often need to be used in a particular order. This documentation doesn’t attempt to cover all of the permutations; consult the zlib manual at http://www.zlib.net/manual.html for authoritative information.
For reading and writing .gz files see the gzip module.
The available exception and functions in this module are:
Exception raised on compression and decompression errors.
Computes an Adler-32 checksum of data. (An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much more quickly.) The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 1 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.
Changed in version 3.0: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use adler32(data) & 0xffffffff.
Compresses the bytes in data, returning a bytes object containing compressed data. level is an integer from 0 to 9 or -1 controlling the level of compression; 1 (Z_BEST_SPEED) is fastest and produces the least compression, 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6). Raises the error exception if any error occurs.
Changed in version 3.6: level can now be used as a keyword parameter.
Returns a compression object, to be used for compressing data streams that won’t fit into memory at once.
level is the compression level – an integer from 0 to 9 or -1. A value of 1 (Z_BEST_SPEED) is fastest and produces the least compression, while a value of 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6).
method is the compression algorithm. Currently, the only supported value is DEFLATED.
The wbits argument controls the size of the history buffer (or the “window size”) used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values, defaulting to 15 (MAX_WBITS):
The memLevel argument controls the amount of memory used for the internal compression state. Valid values range from 1 to 9. Higher values use more memory, but are faster and produce smaller output.
strategy is used to tune the compression algorithm. Possible values are Z_DEFAULT_STRATEGY, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE (zlib 1.2.0.1) and Z_FIXED (zlib 1.2.2.2).
zdict is a predefined compression dictionary. This is a sequence of bytes (such as a bytes object) containing subsequences that are expected to occur frequently in the data that is to be compressed. Those subsequences that are expected to be most common should come at the end of the dictionary.
Changed in version 3.3: Added the zdict parameter and keyword argument support.
Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.
Changed in version 3.0: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.
Decompresses the bytes in data, returning a bytes object containing the uncompressed data. The wbits parameter depends on the format of data, and is discussed further below. If bufsize is given, it is used as the initial size of the output buffer. Raises the error exception if any error occurs.
The wbits parameter controls the size of the history buffer (or “window size”), and what header and trailer format is expected. It is similar to the parameter for compressobj(), but accepts more ranges of values:
When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an error exception. The default wbits value corresponds to the largest window size and requires a zlib header and trailer to be included.
bufsize is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don’t have to get this value exactly right; tuning it will only save a few calls to malloc().
Changed in version 3.6: wbits and bufsize can be used as keyword arguments.
Returns a decompression object, to be used for decompressing data streams that won’t fit into memory at once.
The wbits parameter controls the size of the history buffer (or the “window size”), and what header and trailer format is expected. It has the same meaning as described for decompress().
The zdict parameter specifies a predefined compression dictionary. If provided, this must be the same dictionary as was used by the compressor that produced the data that is to be decompressed.
Note
If zdict is a mutable object (such as a bytearray), you must not modify its contents between the call to decompressobj() and the first call to the decompressor’s decompress() method.
Changed in version 3.3: Added the zdict parameter.
Compression objects support the following methods:
Compress data, returning a bytes object containing compressed data for at least part of the data in data. This data should be concatenated to the output produced by any preceding calls to the compress() method. Some input may be kept in internal buffers for later processing.
All pending input is processed, and a bytes object containing the remaining compressed output is returned. mode can be selected from the constants Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_BLOCK (zlib 1.2.3.4), or Z_FINISH, defaulting to Z_FINISH. Except Z_FINISH, all constants allow compressing further bytestrings of data, while Z_FINISH finishes the compressed stream and prevents compressing any more data. After calling flush() with mode set to Z_FINISH, the compress() method cannot be called again; the only realistic action is to delete the object.
Returns a copy of the compression object. This can be used to efficiently compress a set of data that share a common initial prefix.
Changed in version 3.8: Added copy.copy() and copy.deepcopy() support to compression objects.
Decompression objects support the following methods and attributes:
A bytes object which contains any bytes past the end of the compressed data. That is, this remains b"" until the last byte that contains compression data is available. If the whole bytestring turned out to contain compressed data, this is b"", an empty bytes object.
A bytes object that contains any data that was not consumed by the last decompress() call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent decompress() method call in order to get correct output.
A boolean indicating whether the end of the compressed data stream has been reached.
This makes it possible to distinguish between a properly-formed compressed stream, and an incomplete or truncated one.
New in version 3.3.
Decompress data, returning a bytes object containing the uncompressed data corresponding to at least part of the data in string. This data should be concatenated to the output produced by any preceding calls to the decompress() method. Some of the input data may be preserved in internal buffers for later processing.
If the optional parameter max_length is non-zero then the return value will be no longer than max_length. This may mean that not all of the compressed input can be processed; and unconsumed data will be stored in the attribute unconsumed_tail. This bytestring must be passed to a subsequent call to decompress() if decompression is to continue. If max_length is zero then the whole input is decompressed, and unconsumed_tail is empty.
Changed in version 3.6: max_length can be used as a keyword argument.
All pending input is processed, and a bytes object containing the remaining uncompressed output is returned. After calling flush(), the decompress() method cannot be called again; the only realistic action is to delete the object.
The optional parameter length sets the initial size of the output buffer.
Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point.
Changed in version 3.8: Added copy.copy() and copy.deepcopy() support to decompression objects.
Information about the version of the zlib library in use is available through the following constants:
The version string of the zlib library that was used for building the module. This may be different from the zlib library actually used at runtime, which is available as ZLIB_RUNTIME_VERSION.
The version string of the zlib library actually loaded by the interpreter.
New in version 3.3.
See also
Reading and writing gzip-format files.
The zlib library home page.
The zlib manual explains the semantics and usage of the library’s many functions.


Computes an Adler-32 checksum of data. (An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much more quickly.) The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 1 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.
Changed in version 3.0: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use adler32(data) & 0xffffffff.


Compresses the bytes in data, returning a bytes object containing compressed data. level is an integer from 0 to 9 or -1 controlling the level of compression; 1 (Z_BEST_SPEED) is fastest and produces the least compression, 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6). Raises the error exception if any error occurs.
Changed in version 3.6: level can now be used as a keyword parameter.


Compress data, returning a bytes object containing compressed data for at least part of the data in data. This data should be concatenated to the output produced by any preceding calls to the compress() method. Some input may be kept in internal buffers for later processing.


Returns a copy of the compression object. This can be used to efficiently compress a set of data that share a common initial prefix.


All pending input is processed, and a bytes object containing the remaining compressed output is returned. mode can be selected from the constants Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_BLOCK (zlib 1.2.3.4), or Z_FINISH, defaulting to Z_FINISH. Except Z_FINISH, all constants allow compressing further bytestrings of data, while Z_FINISH finishes the compressed stream and prevents compressing any more data. After calling flush() with mode set to Z_FINISH, the compress() method cannot be called again; the only realistic action is to delete the object.


Returns a compression object, to be used for compressing data streams that won’t fit into memory at once.
level is the compression level – an integer from 0 to 9 or -1. A value of 1 (Z_BEST_SPEED) is fastest and produces the least compression, while a value of 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6).
method is the compression algorithm. Currently, the only supported value is DEFLATED.
The wbits argument controls the size of the history buffer (or the “window size”) used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values, defaulting to 15 (MAX_WBITS):
The memLevel argument controls the amount of memory used for the internal compression state. Valid values range from 1 to 9. Higher values use more memory, but are faster and produce smaller output.
strategy is used to tune the compression algorithm. Possible values are Z_DEFAULT_STRATEGY, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE (zlib 1.2.0.1) and Z_FIXED (zlib 1.2.2.2).
zdict is a predefined compression dictionary. This is a sequence of bytes (such as a bytes object) containing subsequences that are expected to occur frequently in the data that is to be compressed. Those subsequences that are expected to be most common should come at the end of the dictionary.
Changed in version 3.3: Added the zdict parameter and keyword argument support.


Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.
Changed in version 3.0: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.


Decompresses the bytes in data, returning a bytes object containing the uncompressed data. The wbits parameter depends on the format of data, and is discussed further below. If bufsize is given, it is used as the initial size of the output buffer. Raises the error exception if any error occurs.
The wbits parameter controls the size of the history buffer (or “window size”), and what header and trailer format is expected. It is similar to the parameter for compressobj(), but accepts more ranges of values:
When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an error exception. The default wbits value corresponds to the largest window size and requires a zlib header and trailer to be included.
bufsize is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don’t have to get this value exactly right; tuning it will only save a few calls to malloc().
Changed in version 3.6: wbits and bufsize can be used as keyword arguments.


Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point.


Decompress data, returning a bytes object containing the uncompressed data corresponding to at least part of the data in string. This data should be concatenated to the output produced by any preceding calls to the decompress() method. Some of the input data may be preserved in internal buffers for later processing.
If the optional parameter max_length is non-zero then the return value will be no longer than max_length. This may mean that not all of the compressed input can be processed; and unconsumed data will be stored in the attribute unconsumed_tail. This bytestring must be passed to a subsequent call to decompress() if decompression is to continue. If max_length is zero then the whole input is decompressed, and unconsumed_tail is empty.
Changed in version 3.6: max_length can be used as a keyword argument.


A boolean indicating whether the end of the compressed data stream has been reached.
This makes it possible to distinguish between a properly-formed compressed stream, and an incomplete or truncated one.
New in version 3.3.


All pending input is processed, and a bytes object containing the remaining uncompressed output is returned. After calling flush(), the decompress() method cannot be called again; the only realistic action is to delete the object.
The optional parameter length sets the initial size of the output buffer.


A bytes object that contains any data that was not consumed by the last decompress() call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent decompress() method call in order to get correct output.


A bytes object which contains any bytes past the end of the compressed data. That is, this remains b"" until the last byte that contains compression data is available. If the whole bytestring turned out to contain compressed data, this is b"", an empty bytes object.


Returns a decompression object, to be used for decompressing data streams that won’t fit into memory at once.
The wbits parameter controls the size of the history buffer (or the “window size”), and what header and trailer format is expected. It has the same meaning as described for decompress().
The zdict parameter specifies a predefined compression dictionary. If provided, this must be the same dictionary as was used by the compressor that produced the data that is to be decompressed.
Note
If zdict is a mutable object (such as a bytearray), you must not modify its contents between the call to decompressobj() and the first call to the decompressor’s decompress() method.
Changed in version 3.3: Added the zdict parameter.


Exception raised on compression and decompression errors.


The version string of the zlib library actually loaded by the interpreter.
New in version 3.3.


The version string of the zlib library that was used for building the module. This may be different from the zlib library actually used at runtime, which is available as ZLIB_RUNTIME_VERSION.