#14399: zipfile now correctly handles comments added to empty zipfiles.
Patch by Serhiy Storchaka.
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index d9181f2..05c3143 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -651,7 +651,7 @@
-class ZipFile:
+class ZipFile(object):
""" Class with methods to open, read, write, close, list zip files.
z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=False)
@@ -690,7 +690,7 @@
self.compression = compression # Method of compression
self.mode = key = mode.replace('b', '')[0]
self.pwd = None
- self.comment = ''
+ self._comment = ''
# Check if we were passed a file-like object
if isinstance(file, basestring):
@@ -765,7 +765,7 @@
print endrec
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._comment = endrec[_ECD_COMMENT] # archive comment
# "concat" is zero, unless zip was concatenated to another file
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
@@ -864,6 +864,22 @@
"""Set default password for encrypted files."""
self.pwd = pwd
+ @property
+ def comment(self):
+ """The comment text associated with the ZIP file."""
+ return self._comment
+
+ @comment.setter
+ def comment(self, comment):
+ # check for valid comment length
+ if len(comment) >= ZIP_MAX_COMMENT:
+ if self.debug:
+ print('Archive comment is too long; truncating to %d bytes'
+ % ZIP_MAX_COMMENT)
+ comment = comment[:ZIP_MAX_COMMENT]
+ self._comment = comment
+ self._didModify = True
+
def read(self, name, pwd=None):
"""Return file bytes (as a string) for name."""
return self.open(name, "r", pwd).read()
@@ -1243,18 +1259,11 @@
centDirSize = min(centDirSize, 0xFFFFFFFF)
centDirOffset = min(centDirOffset, 0xFFFFFFFF)
- # check for valid comment length
- if len(self.comment) >= ZIP_MAX_COMMENT:
- if self.debug > 0:
- msg = 'Archive comment is too long; truncating to %d bytes' \
- % ZIP_MAX_COMMENT
- self.comment = self.comment[:ZIP_MAX_COMMENT]
-
endrec = struct.pack(structEndArchive, stringEndArchive,
0, 0, centDirCount, centDirCount,
- centDirSize, centDirOffset, len(self.comment))
+ centDirSize, centDirOffset, len(self._comment))
self.fp.write(endrec)
- self.fp.write(self.comment)
+ self.fp.write(self._comment)
self.fp.flush()
if not self._filePassed: