Patch #651621, approved by MvL.
This patch allows ZipFile.writestr() to be called with
an archive file name instead of a ZipInfo instance:
z = ZipFile("myarchive.zip", "w")
z.writestr("foo/baz/file.ext", data)
z.close()
I found the old writestr() method very inconvenient
for simple (but common) things.
If called with a file name instead of a ZipInfo
instance, the date_time is set to the current date/time,
which makes sense to me for anonymous data.
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index 4f2b946..6aed172 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -447,9 +447,16 @@
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
- def writestr(self, zinfo, bytes):
+ def writestr(self, zinfo_or_arcname, bytes):
"""Write a file into the archive. The contents is the string
- 'bytes'."""
+ 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or
+ the name of the file in the archive."""
+ if not isinstance(zinfo_or_arcname, ZipInfo):
+ zinfo = ZipInfo(filename=zinfo_or_arcname,
+ date_time=time.localtime(time.time()))
+ zinfo.compress_type = self.compression
+ else:
+ zinfo = zinfo_or_arcname
self._writecheck(zinfo)
zinfo.file_size = len(bytes) # Uncompressed size
zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum