Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b083cb3

Browse files
committed
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.
1 parent 6c7e326 commit b083cb3

2 files changed

Lines changed: 16 additions & 7 deletions

File tree

Doc/lib/libzipfile.tex

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,13 @@ \subsection{ZipFile Objects \label{zipfile-objects}}
146146
\code{'a'}.
147147
\end{methoddesc}
148148

149-
\begin{methoddesc}{writestr}{zinfo, bytes}
150-
Write the string \var{bytes} to the archive; meta-information is
151-
given as the \class{ZipInfo} instance \var{zinfo}. At least the
152-
filename, date, and time must be given by \var{zinfo}. The archive
153-
must be opened with mode \code{'w'} or \code{'a'}.
149+
\begin{methoddesc}{writestr}{zinfo_or_arcname, bytes}
150+
Write the string \var{bytes} to the archive; \var{zinfo_or_arcname}
151+
is either the file name it will be given in the archive, or a
152+
\class{ZipInfo} instance. If it's an instance, at least the
153+
filename, date, and time must be given. If it's a name, the date
154+
and time is set to the current date and time. The archive must be
155+
opened with mode \code{'w'} or \code{'a'}.
154156
\end{methoddesc}
155157

156158

Lib/zipfile.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -447,9 +447,16 @@ def write(self, filename, arcname=None, compress_type=None):
447447
self.filelist.append(zinfo)
448448
self.NameToInfo[zinfo.filename] = zinfo
449449

450-
def writestr(self, zinfo, bytes):
450+
def writestr(self, zinfo_or_arcname, bytes):
451451
"""Write a file into the archive. The contents is the string
452-
'bytes'."""
452+
'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or
453+
the name of the file in the archive."""
454+
if not isinstance(zinfo_or_arcname, ZipInfo):
455+
zinfo = ZipInfo(filename=zinfo_or_arcname,
456+
date_time=time.localtime(time.time()))
457+
zinfo.compress_type = self.compression
458+
else:
459+
zinfo = zinfo_or_arcname
453460
self._writecheck(zinfo)
454461
zinfo.file_size = len(bytes) # Uncompressed size
455462
zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum

0 commit comments

Comments
 (0)