zipfile - Read and write ZIP files.
| Use Case | Command | Description |
|---|---|---|
| ๐ Open ZIP for reading | zf = ZipFile('archive.zip', 'r') | Open existing archive in read mode |
| โ๏ธ Create new ZIP | zf = ZipFile('new.zip', 'w') | Create or overwrite archive |
| ๐ Append to ZIP | zf = ZipFile('archive.zip', 'a') | Add files to existing archive |
| ๐ค Extract all | zf.extractall('outdir') | Extract everything to a folder |
| ๐ฅ Extract single file | zf.extract('file.txt', 'outdir') | Extract one member |
| ๐ List files | zf.namelist() | Get list of archive member names |
| ๐ Read file content | data = zf.read('file.txt') | Return bytes of a member |
| ๐ Write string to archive | zf.writestr('hello.txt', 'Hello') | Write a string as a file |
| ๐งช Test archive integrity | zf.testzip() | Check CRC of all files; returns first bad name or None |
| ๐ Set password | zf.setpassword(b'secret') | Set default password for encrypted files |
| โ Check if ZIP file | is_zipfile('maybe.zip') | Quick magic number check |
XXX references to utf-8 need further investigation.
๐ Official Python 3.10 zipfile documentation
BadZipFile (alias: BadZipfile, error) โ raised for bad ZIP filesLargeZipFile โ raised when ZIP64 extensions required but disabledPath โ pathlib-compatible interface for zip filesZipFile โ main class for reading/writing ZIP filesPyZipFile โ subclass for creating ZIP archives with Python libraries and packagesZipInfo โ holds information about a single archive memberclass BadZipFile(builtins.Exception)
Aliases: BadZipfile, error (all refer to the same class).
Inherits all methods from Exception and BaseException (__init__, __new__, __str__, __repr__, with_traceback, etc.).
Data descriptors: __weakref__
class LargeZipFile(builtins.Exception)
Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled.
Inherits all methods from Exception and BaseException.
Data descriptors: __weakref__
class Path(builtins.object)
Path(root, at='')
A pathlib-compatible interface for zip files.
Consider a zip file with this structure:
.
โโโ a.txt
โโโ b
โโโ c.txt
โโโ d
โโโ e.txt
Example usage:
>>> data = io.BytesIO()
>>> zf = ZipFile(data, 'w')
>>> zf.writestr('a.txt', 'content of a')
>>> zf.writestr('b/c.txt', 'content of c')
>>> zf.writestr('b/d/e.txt', 'content of e')
>>> zf.filename = 'mem/abcde.zip'
>>> root = Path(zf)
>>> a, b = root.iterdir()
>>> a
... Path('mem/abcde.zip', 'a.txt')
>>> b
... Path('mem/abcde.zip', 'b/')
>>> b.name
... 'b'
>>> c = b / 'c.txt'
>>> c.read_text()
... 'content of c'
>>> c.exists()
... True
>>> str(c).replace(os.sep, posixpath.sep)
... 'mem/abcde.zip/b/c.txt'
Methods:
__init__(self, root, at='') โ Construct from a ZipFile or filename. Note: when the source is an existing ZipFile object, its type will be mutated. If the caller wishes to retain the original type, pass a filename.__repr__(self) โ Return repr(self).__str__(self) โ Return str(self).__truediv__ = joinpath(self, *other)exists(self) โ Check if the entry exists.is_dir(self) โ True if directory.is_file(self) โ True if file.iterdir(self) โ Iterate over directory contents.joinpath(self, *other) โ Join paths.open(self, mode='r', *args, pwd=None, **kwargs) โ Open entry as text or binary following pathlib.Path.open() semantics.read_bytes(self) โ Read as bytes.read_text(self, *args, **kwargs) โ Read as text.Readonly properties: filename, name, parent.
Data descriptors: __dict__, __weakref__.
class PyZipFile(ZipFile)
PyZipFile(file, mode='r', compression=0, allowZip64=True, optimize=-1)
Class to create ZIP archives with Python library files and packages.
Methods defined here:
__init__(self, file, mode='r', compression=0, allowZip64=True, optimize=-1) โ Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'.writepy(self, pathname, basename='', filterfunc=None) โ Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search recursively for *.py and compile to .pyc. If a filterfunc is given, only files/packages for which it returns True are included.Inherits all methods from ZipFile (see below).
class ZipFile(builtins.object)
ZipFile(file, mode='r', compression=0, allowZip64=True, compresslevel=None, *, strict_timestamps=True)
Class with methods to open, read, write, close, list zip files.
Parameters:
file โ path to the file or a file-like object.mode โ 'r' (read), 'w' (write), 'x' (exclusive create), 'a' (append).compression โ ZIP_STORED (0, no compression), ZIP_DEFLATED (8, requires zlib), ZIP_BZIP2 (12, requires bz2), ZIP_LZMA (14, requires lzma).allowZip64 โ if True, use ZIP64 extensions when needed; otherwise raise exception.compresslevel โ None (default) or integer for compression level (0-9 for deflate, 1-9 for bzip2; ignored for stored/lzma).Methods:
__del__(self) โ Call close() if user forgot.__enter__(self)__exit__(self, type, value, traceback)__init__(self, file, mode='r', compression=0, allowZip64=True, compresslevel=None, *, strict_timestamps=True) โ Open the ZIP file.__repr__(self) โ Return repr(self).close(self) โ Close the file; for write/append modes, write ending records.extract(self, member, path=None, pwd=None) โ Extract a member to the current working directory (or path). member can be a filename or ZipInfo.extractall(self, path=None, members=None, pwd=None) โ Extract all members to path (default .). members subset optional.getinfo(self, name) โ Return ZipInfo for given name.infolist(self) โ Return list of ZipInfo objects for all members.namelist(self) โ Return list of file names in the archive.open(self, name, mode='r', pwd=None, *, force_zip64=False) โ Return file-like object for name (string or ZipInfo). mode 'r' or 'w'. pwd for decryption. Use force_zip64 for writing large files (>2 GiB) when size unknown.printdir(self, file=None) โ Print table of contents.read(self, name, pwd=None) โ Return file bytes for name.setpassword(self, pwd) โ Set default password for encrypted files.testzip(self) โ Read all files and check CRC; returns name of first bad file or None.write(self, filename, arcname=None, compress_type=None, compresslevel=None) โ Write the file filename into the archive as arcname.writestr(self, zinfo_or_arcname, data, compress_type=None, compresslevel=None) โ Write a file into the archive. data can be str (encoded UTF-8) or bytes. zinfo_or_arcname is either a ZipInfo instance or the archive name.Data descriptors:
comment โ The comment text associated with the ZIP file.fp โ The file object (None).__dict__, __weakref__class ZipInfo(builtins.object)
ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))
Class with attributes describing each file in the ZIP archive.
Methods:
FileHeader(self, zip64=None) โ Return the per-file header as bytes.__init__(self, filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))__repr__(self) โ Return repr(self).is_dir(self) โ Return True if this archive member is a directory.Class methods:
from_file(filename, arcname=None, *, strict_timestamps=True) โ Construct a ZipInfo from a filesystem file. arcname is the name to use in the archive (default: filename without drive/leading separators).Data descriptors (attributes):
CRCcommentcompress_sizecompress_typecreate_systemcreate_versiondate_timeexternal_attrextraextract_versionfile_sizefilenameflag_bitsheader_offsetinternal_attrorig_filenamereservedvolumeis_zipfile(filename) โ Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object.ZIP_STORED = 0ZIP_DEFLATED = 8ZIP_BZIP2 = 12ZIP_LZMA = 14__all__ = ['BadZipFile', 'BadZipfile', 'error', 'ZIP_STORED', 'ZIP_DEFLATED', ...]/usr/lib/python3.10/zipfile.py
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 18:14 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format