[Python-checkins] bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)

Miss Islington (bot) webhook-mailer at python.org
Mon Sep 28 16:18:51 EDT 2020

commit: 048f54dc75d51e8a1c5822ab7b2828295192aaa5
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2020-09-28T13:18:47-07:00

bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)

(cherry picked from commit ff9147d93b868f0e13b9fe14e2a76c2879f6787b)

Co-authored-by: Jan Mazur <16736821+mzr at users.noreply.github.com>

A Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst
M Lib/test/test_zipfile.py
M Lib/zipfile.py

diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py
index b7bc218d17a3d..999197a0e32dc 100644
--- a/Lib/test/test_zipfile.py
+++ b/Lib/test/test_zipfile.py
@@ -1855,11 +1855,14 @@ def test_comments(self):
             self.assertEqual(zipf.comment, b"an updated comment")
         # check that comments are correctly shortened in append mode
+        # and the file is indeed truncated
         with zipfile.ZipFile(TESTFN,mode="w") as zipf:
             zipf.comment = b"original comment that's longer"
             zipf.writestr("foo.txt", "O, for a Muse of Fire!")
+        original_zip_size = os.path.getsize(TESTFN)
         with zipfile.ZipFile(TESTFN,mode="a") as zipf:
             zipf.comment = b"shorter comment"
+        self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
         with zipfile.ZipFile(TESTFN,mode="r") as zipf:
             self.assertEqual(zipf.comment, b"shorter comment")
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index 915698f9e0588..816f8582bbf6d 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -1918,6 +1918,8 @@ def _write_end_record(self):
                              centDirSize, centDirOffset, len(self._comment))
+        if self.mode == "a":
+            self.fp.truncate()
     def _fpclose(self, fp):
diff --git a/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst b/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst
new file mode 100644
index 0000000000000..f71a7a1e697a4
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-04-03-16-13-59.bpo-40105.hfM2c0.rst
@@ -0,0 +1,2 @@
+ZipFile truncates files to avoid corruption when a shorter comment is provided
+in append ("a") mode. Patch by Jan Mazur.

More information about the Python-checkins mailing list