Python Glossary Русский

all Python 3zipfileterm

zipfile.PyZipFile

ZIP archives

A ZipFile subclass for packaging Python modules: writepy() compiles .py files and stores .pyc in the archive.

Syntax

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

The resulting archive can be put on sys.path and imported from, but it usually holds only .pyc files — no sources — and bytecode is tied to the interpreter version: an archive built on 3.14 will not import on 3.13. writepy() treats a directory as a package only if it has __init__.py; otherwise it packs the .py files in it as separate modules. For shipping a program, zipapp is usually the better tool.

Examples

import sys, zipfile
with open('mymod.py', 'w', encoding='utf-8') as f:
    f.write('X = 42\n')
with zipfile.PyZipFile('lib.zip', 'w') as z:
    z.writepy('mymod.py')
    print(z.namelist())  # → ['mymod.pyc'] — исходника в архиве нет
sys.path.insert(0, 'lib.zip')
import mymod
print(mymod.X)  # → 42

See also

Open in the full glossarydocs.python.orgReport an inaccuracy