diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index 2851051425bf12..687e43df780d65 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -1856,11 +1856,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 915698f9e05889..816f8582bbf6d5 100644 --- a/Lib/zipfile.py +++ b/Lib/zipfile.py @@ -1918,6 +1918,8 @@ def _write_end_record(self): centDirSize, centDirOffset, len(self._comment)) self.fp.write(endrec) self.fp.write(self._comment) + if self.mode == "a": + self.fp.truncate() self.fp.flush() 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 00000000000000..f71a7a1e697a48 --- /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. pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy