Skip to content

Commit ff9147d

Browse files
authored
bpo-40105: ZipFile truncate in append mode with shorter comment (GH-19337)
1 parent a195bce commit ff9147d

File tree

3 files changed

+7
-0
lines changed

3 files changed

+7
-0
lines changed

Lib/test/test_zipfile.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1856,11 +1856,14 @@ def test_comments(self):
18561856
self.assertEqual(zipf.comment, b"an updated comment")
18571857

18581858
# check that comments are correctly shortened in append mode
1859+
# and the file is indeed truncated
18591860
with zipfile.ZipFile(TESTFN,mode="w") as zipf:
18601861
zipf.comment = b"original comment that's longer"
18611862
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1863+
original_zip_size = os.path.getsize(TESTFN)
18621864
with zipfile.ZipFile(TESTFN,mode="a") as zipf:
18631865
zipf.comment = b"shorter comment"
1866+
self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
18641867
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
18651868
self.assertEqual(zipf.comment, b"shorter comment")
18661869

Lib/zipfile.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1918,6 +1918,8 @@ def _write_end_record(self):
19181918
centDirSize, centDirOffset, len(self._comment))
19191919
self.fp.write(endrec)
19201920
self.fp.write(self._comment)
1921+
if self.mode == "a":
1922+
self.fp.truncate()
19211923
self.fp.flush()
19221924

19231925
def _fpclose(self, fp):
Lines 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)
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