]> granicus.if.org Git - python/commitdiff
Patch #651621, approved by MvL.
authorJust van Rossum <just@letterror.com>
Thu, 12 Dec 2002 12:23:32 +0000 (12:23 +0000)
committerJust van Rossum <just@letterror.com>
Thu, 12 Dec 2002 12:23:32 +0000 (12:23 +0000)
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.

Doc/lib/libzipfile.tex
Lib/zipfile.py

index a6430cb2d62d392bc6b864e91a52547a7102cecc..69e7878b8a9af934ea6c7d5ad70ee712812a11ad 100644 (file)
@@ -146,11 +146,13 @@ cat myzip.zip >> python.exe
   \code{'a'}. 
 \end{methoddesc}
 
-\begin{methoddesc}{writestr}{zinfo, bytes}
-  Write the string \var{bytes} to the archive; meta-information is
-  given as the \class{ZipInfo} instance \var{zinfo}.  At least the
-  filename, date, and time must be given by \var{zinfo}.  The archive
-  must be opened with mode \code{'w'} or \code{'a'}.
+\begin{methoddesc}{writestr}{zinfo_or_arcname, bytes}
+  Write the string \var{bytes} to the archive; \var{zinfo_or_arcname}
+  is either the file name it will be given in the archive, or a
+  \class{ZipInfo} instance.  If it's an instance, at least the
+  filename, date, and time must be given.  If it's a name, the date
+  and time is set to the current date and time. The archive must be
+  opened with mode \code{'w'} or \code{'a'}.
 \end{methoddesc}
 
 
index 4f2b9468a941ffecc3d520e0bb3cd4e970592f75..6aed1729996ced1d046ae92e5ba1f6c441d6eb10 100644 (file)
@@ -447,9 +447,16 @@ class ZipFile:
         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