Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e400840

Browse filesBrowse files
miss-islingtonmzr
andauthored
bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)
(cherry picked from commit ff9147d) Co-authored-by: Jan Mazur <16736821+mzr@users.noreply.github.com>
1 parent e0e614c commit e400840
Copy full SHA for e400840

File tree

Expand file treeCollapse file tree

3 files changed

+7
-0
lines changed
Filter options
Expand file treeCollapse file tree

3 files changed

+7
-0
lines changed

‎Lib/test/test_zipfile.py

Copy file name to clipboardExpand all lines: Lib/test/test_zipfile.py
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,11 +1844,14 @@ def test_comments(self):
18441844
self.assertEqual(zipf.comment, b"an updated comment")
18451845

18461846
# check that comments are correctly shortened in append mode
1847+
# and the file is indeed truncated
18471848
with zipfile.ZipFile(TESTFN,mode="w") as zipf:
18481849
zipf.comment = b"original comment that's longer"
18491850
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1851+
original_zip_size = os.path.getsize(TESTFN)
18501852
with zipfile.ZipFile(TESTFN,mode="a") as zipf:
18511853
zipf.comment = b"shorter comment"
1854+
self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
18521855
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
18531856
self.assertEqual(zipf.comment, b"shorter comment")
18541857

‎Lib/zipfile.py

Copy file name to clipboardExpand all lines: Lib/zipfile.py
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1942,6 +1942,8 @@ def _write_end_record(self):
19421942
centDirSize, centDirOffset, len(self._comment))
19431943
self.fp.write(endrec)
19441944
self.fp.write(self._comment)
1945+
if self.mode == "a":
1946+
self.fp.truncate()
19451947
self.fp.flush()
19461948

19471949
def _fpclose(self, fp):
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
ZipFile truncates files to avoid corruption when a shorter comment is provided
2+
in append ("a") mode. Patch by Jan Mazur.

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.