[issue41035] zipfile.Path does not work properly with zip archives where paths start with /

sorrow report at bugs.python.org
Mon Jun 22 14:39:36 EDT 2020


sorrow <lynx1534 at gmail.com> added the comment:

Here's what I came up with:

```python
class ZipPath(zipfile.Path):
def __init__(self, root, at=""):
    super().__init__(root, at)
    if not at.startswith("/") and self.root.namelist()[0].startswith("/"):
        self.at = f"/{at}"

def __repr__(self):
    return (
        f"{self.__class__.__name__}({self.root.filename!r}, "
        f"{self.at.lstrip('/')!r})"
    )

def __str__(self):
    return posixpath.join(self.root.filename, self.at.lstrip("/"))

def _is_child(self, path):
    return posixpath.dirname(path.at.strip("/")) == self.at.strip("/")

def _next(self, at):
    return self.__class__(self.root, at)
```

Pretty simple. The main things are going on in `__init__` and `_is_child` methods. These changes are enough for `iteritems()` to work. I decided to include the leading slash in the `at`, but strip it for the outside world (__str__ and __repr__). Also, I had to override the `_next` method because it makes `Path` objects no matter what class it's called from.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41035>
_______________________________________


More information about the Python-bugs-list mailing list