Skip to content

Commit 84cb5de

Browse files
committed
gh-126565: Skip zipfile.Path.exists check in write mode
When `zipfile.Path.open` is called, the implementation will check whether the path already exists in the ZIP file. However, this check is only required when the ZIP file is in read mode. By swapping arguments of the `and` operator, the short-circuiting will prevent the check from being run in write mode. This change will improve the performance of `open()`, because checking whether a file exists is slow in write mode, especially when the archive has many members.
1 parent 06a8b0b commit 84cb5de

2 files changed

Lines changed: 7 additions & 1 deletion

File tree

Lib/zipfile/_path/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ def open(self, mode='r', *args, pwd=None, **kwargs):
339339
if self.is_dir():
340340
raise IsADirectoryError(self)
341341
zip_mode = mode[0]
342-
if not self.exists() and zip_mode == 'r':
342+
if zip_mode == 'r' and not self.exists():
343343
raise FileNotFoundError(self)
344344
stream = self.root.open(self.at, zip_mode, pwd=pwd)
345345
if 'b' in mode:
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Calling :meth:`zipfile.Path.open` no longer checks for an existing file in
2+
write mode. Checking for file existence in ZIP files opened in write mode is
3+
particularly slow, because the list of members cannot be cached up-front. As
4+
the check is irrelevant for the write mode any, it will no longer be performed
5+
resulting in a performance improvement especially with ZIP files that have many
6+
members.

0 commit comments

Comments
 (0)