Index: Lib/zipfile.py =================================================================== --- Lib/zipfile.py (revision 82847) +++ Lib/zipfile.py (working copy) @@ -660,7 +660,7 @@ self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] self.pwd = None - self.comment = '' + self.comment = self._original_comment = '' # Check if we were passed a file-like object if isinstance(file, basestring): @@ -725,6 +725,7 @@ size_cd = endrec[_ECD_SIZE] # bytes in central directory offset_cd = endrec[_ECD_OFFSET] # offset of central directory self.comment = endrec[_ECD_COMMENT] # archive comment + self._original_comment = self.comment # "concat" is zero, unless zip was concatenated to another file concat = endrec[_ECD_LOCATION] - size_cd - offset_cd @@ -777,7 +778,6 @@ if self.debug > 2: print "total", total - def namelist(self): """Return a list of file names in the archive.""" l = [] @@ -1116,6 +1116,9 @@ if self.fp is None: return + if self.comment != self._original_comment: + self._didModify = True + if self.mode in ("w", "a") and self._didModify: # write ending records count = 0 pos1 = self.fp.tell() @@ -1210,11 +1213,13 @@ self.comment = self.comment[:ZIP_MAX_COMMENT] endrec = struct.pack(structEndArchive, stringEndArchive, - 0, 0, centDirCount, centDirCount, - centDirSize, centDirOffset, len(self.comment)) + 0, 0, centDirCount, centDirCount, centDirSize, + centDirOffset, len(self.comment)) self.fp.write(endrec) self.fp.write(self.comment) self.fp.flush() + if len(self.comment) < len(self._original_comment): + self.fp.truncate() if not self._filePassed: self.fp.close() Index: Lib/test/test_zipfile.py =================================================================== --- Lib/test/test_zipfile.py (revision 82847) +++ Lib/test/test_zipfile.py (working copy) @@ -864,6 +864,24 @@ with zipfile.ZipFile(TESTFN, mode="r") as zipf: self.assertEqual(zipf.comment, comment2) + # check that comments are correctly modified in append mode + with zipfile.ZipFile(TESTFN,mode="w") as zipf: + zipf.comment = "original comment" + zipf.writestr("foo.txt", "O, for a Muse of Fire!") + with zipfile.ZipFile(TESTFN,mode="a") as zipf: + zipf.comment = "an updated comment" + with zipfile.ZipFile(TESTFN,mode="r") as zipf: + self.assertEqual(zipf.comment, "an updated comment") + + # check that comments are correctly shortened in append mode + with zipfile.ZipFile(TESTFN,mode="w") as zipf: + zipf.comment = "original comment that's longer" + zipf.writestr("foo.txt", "O, for a Muse of Fire!") + with zipfile.ZipFile(TESTFN,mode="a") as zipf: + zipf.comment = "shorter comment" + with zipfile.ZipFile(TESTFN,mode="r") as zipf: + self.assertEqual(zipf.comment, "shorter comment") + def tearDown(self): unlink(TESTFN) unlink(TESTFN2)