https://github.com/python/cpython/commit/dc78afeff8786b5d4fb3b0602426204eeee6bfc1 commit: dc78afeff8786b5d4fb3b0602426204eeee6bfc1 branch: main author: Pengyu Lee <[email protected]> committer: JelleZijlstra <[email protected]> date: 2026-10-23T12:50:21-07:00 summary:
gh-156078: Prevent ZipFile.mkdir() during an active write (#156079) Fix `ZipFile.mkdir()` so that it raises `ValueError` when another writable member handle returned by `ZipFile.open(..., mode="w")` is still open. Co-authored-by: Stan Ulbrych <[email protected]> files: A Misc/NEWS.d/next/Library/2026-08-20-09-56-45.gh-issue-156078.-E7gZc.rst M Lib/test/test_zipfile/test_core.py M Lib/zipfile/__init__.py diff --git a/Lib/test/test_zipfile/test_core.py b/Lib/test/test_zipfile/test_core.py index cb9061042937cf..ab1995e91286e6 100644 --- a/Lib/test/test_zipfile/test_core.py +++ b/Lib/test/test_zipfile/test_core.py @@ -4615,6 +4615,8 @@ def test_open_conflicting_handles(self): zipf.writestr('str', 'abcde') with self.assertRaises(ValueError): zipf.write(__file__, 'file') + with self.assertRaises(ValueError): + zipf.mkdir('directory') with self.assertRaises(ValueError): zipf.close() w1.write(msg2) @@ -5646,6 +5648,9 @@ def test_mkdir(self): zf.extractall(target) self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"}) + with self.assertRaises(ValueError): + zf.mkdir("closed") + def test_create_directory_with_write(self): with zipfile.ZipFile(TESTFN, "w") as zf: zf.writestr(zipfile.ZipInfo('directory/'), '') diff --git a/Lib/zipfile/__init__.py b/Lib/zipfile/__init__.py index 4c5eb1d04eb4d3..5963f84bdad299 100644 --- a/Lib/zipfile/__init__.py +++ b/Lib/zipfile/__init__.py @@ -2630,6 +2630,15 @@ def mkdir(self, zinfo_or_directory_name, mode=511): else: raise TypeError("Expected type str or ZipInfo") + if not self.fp: + raise ValueError( + "Attempt to write to ZIP archive that was already closed" + ) + if self._writing: + raise ValueError( + "Can't write to ZIP archive while an open writing handle exists." + ) + with self._lock: if self._seekable: self.fp.seek(self.start_dir) diff --git a/Misc/NEWS.d/next/Library/2026-08-20-09-56-45.gh-issue-156078.-E7gZc.rst b/Misc/NEWS.d/next/Library/2026-08-20-09-56-45.gh-issue-156078.-E7gZc.rst new file mode 100644 index 00000000000000..d2a3a219fa8958 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-20-09-56-45.gh-issue-156078.-E7gZc.rst @@ -0,0 +1,2 @@ +:meth:`zipfile.ZipFile.mkdir` now raises :exc:`ValueError` when the archive +is closed or when a writable member handle is open. _______________________________________________ Python-checkins mailing list -- [email protected] To unsubscribe send an email to [email protected] https://mail.python.org/mailman3//lists/python-checkins.python.org Member address: [email protected]
