Skip to content

Commit 33e067d

Browse files
jaracowarsaw
authored andcommitted
Add support for .parent and .joinpath in zipfile.Path (#13213)
1 parent afd1e6d commit 33e067d

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Lib/test/test_zipfile.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2481,6 +2481,14 @@ def test_read(self):
24812481
assert a.read_text() == "content of a"
24822482
assert a.read_bytes() == b"content of a"
24832483

2484+
def test_joinpath(self):
2485+
for zipfile_abcde in self.zipfile_abcde():
2486+
root = zipfile.Path(zipfile_abcde)
2487+
a = root.joinpath("a")
2488+
assert a.is_file()
2489+
e = root.joinpath("b").joinpath("d").joinpath("e.txt")
2490+
assert e.read_text() == "content of e"
2491+
24842492
def test_traverse_truediv(self):
24852493
for zipfile_abcde in self.zipfile_abcde():
24862494
root = zipfile.Path(zipfile_abcde)
@@ -2502,5 +2510,11 @@ def test_traverse_pathlike(self):
25022510
root = zipfile.Path(zipfile_abcde)
25032511
root / pathlib.Path("a")
25042512

2513+
def test_parent(self):
2514+
for zipfile_abcde in self.zipfile_abcde():
2515+
root = zipfile.Path(zipfile_abcde)
2516+
assert (root / 'a').parent.at == ''
2517+
assert (root / 'a' / 'b').parent.at == 'a/'
2518+
25052519
if __name__ == "__main__":
25062520
unittest.main()

Lib/zipfile.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2218,12 +2218,14 @@ def __str__(self):
22182218
def __repr__(self):
22192219
return self.__repr.format(self=self)
22202220

2221-
def __truediv__(self, add):
2221+
def joinpath(self, add):
22222222
next = posixpath.join(self.at, add)
22232223
next_dir = posixpath.join(self.at, add, "")
22242224
names = self._names()
22252225
return self._next(next_dir if next not in names and next_dir in names else next)
22262226

2227+
__truediv__ = joinpath
2228+
22272229
@staticmethod
22282230
def _add_implied_dirs(names):
22292231
return names + [
@@ -2232,6 +2234,13 @@ def _add_implied_dirs(names):
22322234
if name and name + "/" not in names
22332235
]
22342236

2237+
@property
2238+
def parent(self):
2239+
parent_at = posixpath.dirname(self.at)
2240+
if parent_at:
2241+
parent_at += '/'
2242+
return self._next(parent_at)
2243+
22352244
def _names(self):
22362245
return self._add_implied_dirs(self.root.namelist())
22372246

0 commit comments

Comments
 (0)