PyDocs

Nav

Data Compression and Archiving

Path

zipfile

class (source)
  • Path(root, at='')
A :class:`importlib.resources.abc.Traversable` interface for zip files.

Implements many of the features users enjoy from
:class:`pathlib.Path`.

Consider a zip file with this structure::

    .
    ├── a.txt
    └── b
        ├── c.txt
        └── d
            └── e.txt

>>> 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'

Path accepts the zipfile object itself or a filename

>>> path = Path(zf)

From there, several path operations are available.

Directory iteration (including the zip file itself):

>>> a, b = path.iterdir()
>>> a
Path('mem/abcde.zip', 'a.txt')
>>> b
Path('mem/abcde.zip', 'b/')

name property:

>>> b.name
'b'

join with divide operator:

>>> c = b / 'c.txt'
>>> c
Path('mem/abcde.zip', 'b/c.txt')
>>> c.name
'c.txt'

Read text:

>>> c.read_text(encoding='utf-8')
'content of c'

existence:

>>> c.exists()
True
>>> (b / 'missing.txt').exists()
False

Coercion to string:

>>> import os
>>> str(c).replace(os.sep, posixpath.sep)
'mem/abcde.zip/b/c.txt'

At the root, ``name``, ``filename``, and ``parent``
resolve to the zipfile.

>>> str(path)
'mem/abcde.zip'
>>> path.name
'abcde.zip'
>>> path.filename == pathlib.Path('mem/abcde.zip')
True
>>> str(path.parent)
'mem'

If the zipfile has no filename, such attributes are not
valid and accessing them will raise an Exception.

>>> zf.filename = None
>>> path.name
Traceback (most recent call last):
...
TypeError: ...

>>> path.filename
Traceback (most recent call last):
...
TypeError: ...

>>> path.parent
Traceback (most recent call last):
...
TypeError: ...

# workaround python/cpython#106763
>>> pass
Members of Path

e

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

i

is_dir
Return True if the current context references a directory.
is_file
Return True if the current context references a file.
is_symlink
Return whether this path is a symlink.
iterdir
Enumerate the children of the current directory.

j

joinpath
Return a new Path object with each of the other arguments joined.

n

name
The final path component.

o

open
Open this entry as text or binary following the semantics of ``pathlib.Path.open()`` by passing arguments through to io.TextIOWrapper().

r

read_bytes
Read the current file as bytes.
read_text
Read the current file as unicode text.

s

stem
The final path component, without its suffix.
suffix
The last dot-separated portion of the final component, if any.
suffixes
A list of the path’s suffixes, commonly called file extensions.
0 Examples
No examples for zipfile/Path.
See Also
No see-alsos for zipfile/Path
0 Notes
No notes for Path