To learn more about Python Zip applications, check out Python’s zipapp: Build Executable Zip Applications.
Exploring Additional Classes From zipfile
00:20 In this section of the course, you’ll learn the basics of these classes and their main features. When you open a ZIP file with your favorite archiver application, you see the archive’s internal structure.
00:32 You may have files at the root of the archive. You may also have subdirectories with more files. The archive looks like a normal directory on your file system, with each file located at a specific path.
You can get the name of the file with
.name, and you can check if the path points to a regular file with
.is_file(). You can check if a given file exists inside a particular ZIP file, and you can read the text of a file.
The main difference from
ZipFile is that the initializer of
PyZipFile takes an optional argument called
optimize, which allows you to optimize the Python code by compiling it into bytecode before archiving it.
PyZipFile provides the same interface as
ZipFile with the addition of
.writepy(). This method can take a Python file (
.py) as an argument and add it to the underlying ZIP file. If
-1 (the default), then the
.py file is automatically compiled to a
.pyc file and then added to the target archive. Why does this happen?
03:47 Since version 2.3, the Python interpreter has supported importing Python code from ZIP files, a capability known as Zip imports. This convenient feature allows you to create importable ZIP files to distribute your modules and packages as a single archive.
PyZipFile is helpful when you need to generate importable ZIP files. Packaging the
.pyc file rather than the
.py file makes the importing process much more efficient because it skips the compilation step.
This becomes clear when you list the archive’s content using
.printdir(). Once you have
hello.py bundled into a ZIP file, then you can use Python’s import system to import this module from the containing archive.
The first step to import code from a ZIP file is to make the file available in
sys.path. This variable holds a list of strings that specify Python’s search path for modules. To add an item to
sys.path, you can use
.insert(). For this example to work, you’ll need to change the placeholder path and pass the path to
hello.zip on your file system. Once your importable ZIP file is in this list, then you can import your code just like you would do with a regular module.
Finally, consider the
hello/ subdirectory in your working folder. It contains a small Python package with a structure seen on-screen. The
__init__.py module turns the
hello/ directory into a Python package.
Become a Member to join the conversation.