Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
zipfile.PyZipFile Class Reference
Inheritance diagram for zipfile.PyZipFile:
Inheritance graph
[legend]
Collaboration diagram for zipfile.PyZipFile:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def writepy
def __enter__
def __exit__
def namelist
def infolist
def printdir
def testzip
def getinfo
def setpassword
def read
def open
def extract
def extractall
def write
def writestr
def close

Public Attributes

 debug
 NameToInfo
 filelist
 compression
 mode
 pwd
 comment
 filename
 start_dir

Static Public Attributes

 fp = None

Private Member Functions

def _get_codename

Private Attributes

 _optimize

Detailed Description

Class to create ZIP archives with Python library files and packages.

Definition at line 1305 of file zipfile.py.


Constructor & Destructor Documentation

def zipfile.PyZipFile.__init__ (   self,
  file,
  mode = "r",
  compression = ZIP_STORED,
  allowZip64 = False,
  optimize = -1 
)

Definition at line 1309 of file zipfile.py.

01309 
01310                  allowZip64=False, optimize=-1):
01311         ZipFile.__init__(self, file, mode=mode, compression=compression,
01312                          allowZip64=allowZip64)
01313         self._optimize = optimize

Here is the caller graph for this function:


Member Function Documentation

def zipfile.ZipFile.__enter__ (   self) [inherited]

Definition at line 743 of file zipfile.py.

00743 
00744     def __enter__(self):
00745         return self

def zipfile.ZipFile.__exit__ (   self,
  type,
  value,
  traceback 
) [inherited]

Definition at line 746 of file zipfile.py.

00746 
00747     def __exit__(self, type, value, traceback):
00748         self.close()

def zipfile.PyZipFile._get_codename (   self,
  pathname,
  basename 
) [private]
Return (filename, archivename) for the path.

Given a module name path, return the correct file path and
archive name, compiling if necessary.  For example, given
/python/lib/string, return (/python/lib/string.pyc, string).

Definition at line 1379 of file zipfile.py.

01379 
01380     def _get_codename(self, pathname, basename):
01381         """Return (filename, archivename) for the path.
01382 
01383         Given a module name path, return the correct file path and
01384         archive name, compiling if necessary.  For example, given
01385         /python/lib/string, return (/python/lib/string.pyc, string).
01386         """
01387         def _compile(file, optimize=-1):
01388             import py_compile
01389             if self.debug:
01390                 print("Compiling", file)
01391             try:
01392                 py_compile.compile(file, doraise=True, optimize=optimize)
01393             except py_compile.PyCompileError as error:
01394                 print(err.msg)
01395                 return False
01396             return True
01397 
01398         file_py  = pathname + ".py"
01399         file_pyc = pathname + ".pyc"
01400         file_pyo = pathname + ".pyo"
01401         pycache_pyc = imp.cache_from_source(file_py, True)
01402         pycache_pyo = imp.cache_from_source(file_py, False)
01403         if self._optimize == -1:
01404             # legacy mode: use whatever file is present
01405             if (os.path.isfile(file_pyo) and
01406                 os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime):
01407                 # Use .pyo file.
01408                 arcname = fname = file_pyo
01409             elif (os.path.isfile(file_pyc) and
01410                   os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
01411                 # Use .pyc file.
01412                 arcname = fname = file_pyc
01413             elif (os.path.isfile(pycache_pyc) and
01414                   os.stat(pycache_pyc).st_mtime >= os.stat(file_py).st_mtime):
01415                 # Use the __pycache__/*.pyc file, but write it to the legacy pyc
01416                 # file name in the archive.
01417                 fname = pycache_pyc
01418                 arcname = file_pyc
01419             elif (os.path.isfile(pycache_pyo) and
01420                   os.stat(pycache_pyo).st_mtime >= os.stat(file_py).st_mtime):
01421                 # Use the __pycache__/*.pyo file, but write it to the legacy pyo
01422                 # file name in the archive.
01423                 fname = pycache_pyo
01424                 arcname = file_pyo
01425             else:
01426                 # Compile py into PEP 3147 pyc file.
01427                 if _compile(file_py):
01428                     fname = (pycache_pyc if __debug__ else pycache_pyo)
01429                     arcname = (file_pyc if __debug__ else file_pyo)
01430                 else:
01431                     fname = arcname = file_py
01432         else:
01433             # new mode: use given optimization level
01434             if self._optimize == 0:
01435                 fname = pycache_pyc
01436                 arcname = file_pyc
01437             else:
01438                 fname = pycache_pyo
01439                 arcname = file_pyo
01440             if not (os.path.isfile(fname) and
01441                     os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
01442                 if not _compile(file_py, optimize=self._optimize):
01443                     fname = arcname = file_py
01444         archivename = os.path.split(arcname)[1]
01445         if basename:
01446             archivename = "%s/%s" % (basename, archivename)
01447         return (fname, archivename)
01448 

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.ZipFile.close (   self) [inherited]
Close the file, and for mode "w" and "a" write the ending
records.

Definition at line 1195 of file zipfile.py.

01195 
01196     def close(self):
01197         """Close the file, and for mode "w" and "a" write the ending
01198         records."""
01199         if self.fp is None:
01200             return
01201 
01202         if self.mode in ("w", "a") and self._didModify: # write ending records
01203             count = 0
01204             pos1 = self.fp.tell()
01205             for zinfo in self.filelist:         # write central directory
01206                 count = count + 1
01207                 dt = zinfo.date_time
01208                 dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
01209                 dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
01210                 extra = []
01211                 if zinfo.file_size > ZIP64_LIMIT \
01212                         or zinfo.compress_size > ZIP64_LIMIT:
01213                     extra.append(zinfo.file_size)
01214                     extra.append(zinfo.compress_size)
01215                     file_size = 0xffffffff
01216                     compress_size = 0xffffffff
01217                 else:
01218                     file_size = zinfo.file_size
01219                     compress_size = zinfo.compress_size
01220 
01221                 if zinfo.header_offset > ZIP64_LIMIT:
01222                     extra.append(zinfo.header_offset)
01223                     header_offset = 0xffffffff
01224                 else:
01225                     header_offset = zinfo.header_offset
01226 
01227                 extra_data = zinfo.extra
01228                 if extra:
01229                     # Append a ZIP64 field to the extra's
01230                     extra_data = struct.pack(
01231                             '<HH' + 'Q'*len(extra),
01232                             1, 8*len(extra), *extra) + extra_data
01233 
01234                     extract_version = max(45, zinfo.extract_version)
01235                     create_version = max(45, zinfo.create_version)
01236                 else:
01237                     extract_version = zinfo.extract_version
01238                     create_version = zinfo.create_version
01239 
01240                 try:
01241                     filename, flag_bits = zinfo._encodeFilenameFlags()
01242                     centdir = struct.pack(structCentralDir,
01243                         stringCentralDir, create_version,
01244                         zinfo.create_system, extract_version, zinfo.reserved,
01245                         flag_bits, zinfo.compress_type, dostime, dosdate,
01246                         zinfo.CRC, compress_size, file_size,
01247                         len(filename), len(extra_data), len(zinfo.comment),
01248                         0, zinfo.internal_attr, zinfo.external_attr,
01249                         header_offset)
01250                 except DeprecationWarning:
01251                     print((structCentralDir, stringCentralDir, create_version,
01252                         zinfo.create_system, extract_version, zinfo.reserved,
01253                         zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
01254                         zinfo.CRC, compress_size, file_size,
01255                         len(zinfo.filename), len(extra_data), len(zinfo.comment),
01256                         0, zinfo.internal_attr, zinfo.external_attr,
01257                         header_offset), file=sys.stderr)
01258                     raise
01259                 self.fp.write(centdir)
01260                 self.fp.write(filename)
01261                 self.fp.write(extra_data)
01262                 self.fp.write(zinfo.comment)
01263 
01264             pos2 = self.fp.tell()
01265             # Write end-of-zip-archive record
01266             centDirCount = count
01267             centDirSize = pos2 - pos1
01268             centDirOffset = pos1
01269             if (centDirCount >= ZIP_FILECOUNT_LIMIT or
01270                 centDirOffset > ZIP64_LIMIT or
01271                 centDirSize > ZIP64_LIMIT):
01272                 # Need to write the ZIP64 end-of-archive records
01273                 zip64endrec = struct.pack(
01274                         structEndArchive64, stringEndArchive64,
01275                         44, 45, 45, 0, 0, centDirCount, centDirCount,
01276                         centDirSize, centDirOffset)
01277                 self.fp.write(zip64endrec)
01278 
01279                 zip64locrec = struct.pack(
01280                         structEndArchive64Locator,
01281                         stringEndArchive64Locator, 0, pos2, 1)
01282                 self.fp.write(zip64locrec)
01283                 centDirCount = min(centDirCount, 0xFFFF)
01284                 centDirSize = min(centDirSize, 0xFFFFFFFF)
01285                 centDirOffset = min(centDirOffset, 0xFFFFFFFF)
01286 
01287             # check for valid comment length
01288             if len(self.comment) >= ZIP_MAX_COMMENT:
01289                 if self.debug > 0:
01290                     msg = 'Archive comment is too long; truncating to %d bytes' \
01291                           % ZIP_MAX_COMMENT
01292                 self.comment = self.comment[:ZIP_MAX_COMMENT]
01293 
01294             endrec = struct.pack(structEndArchive, stringEndArchive,
01295                                  0, 0, centDirCount, centDirCount,
01296                                  centDirSize, centDirOffset, len(self.comment))
01297             self.fp.write(endrec)
01298             self.fp.write(self.comment)
01299             self.fp.flush()
01300 
01301         if not self._filePassed:
01302             self.fp.close()
01303         self.fp = None
01304 

Here is the caller graph for this function:

def zipfile.ZipFile.extract (   self,
  member,
  path = None,
  pwd = None 
) [inherited]
Extract a member from the archive to the current working directory,
   using its full name. Its file information is extracted as accurately
   as possible. `member' may be a filename or a ZipInfo object. You can
   specify a different directory using `path'.

Definition at line 978 of file zipfile.py.

00978 
00979     def extract(self, member, path=None, pwd=None):
00980         """Extract a member from the archive to the current working directory,
00981            using its full name. Its file information is extracted as accurately
00982            as possible. `member' may be a filename or a ZipInfo object. You can
00983            specify a different directory using `path'.
00984         """
00985         if not isinstance(member, ZipInfo):
00986             member = self.getinfo(member)
00987 
00988         if path is None:
00989             path = os.getcwd()
00990 
00991         return self._extract_member(member, path, pwd)

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.ZipFile.extractall (   self,
  path = None,
  members = None,
  pwd = None 
) [inherited]
Extract all members from the archive to the current working
   directory. `path' specifies a different directory to extract to.
   `members' is optional and must be a subset of the list returned
   by namelist().

Definition at line 992 of file zipfile.py.

00992 
00993     def extractall(self, path=None, members=None, pwd=None):
00994         """Extract all members from the archive to the current working
00995            directory. `path' specifies a different directory to extract to.
00996            `members' is optional and must be a subset of the list returned
00997            by namelist().
00998         """
00999         if members is None:
01000             members = self.namelist()
01001 
01002         for zipinfo in members:
01003             self.extract(zipinfo, path, pwd)

Here is the call graph for this function:

def zipfile.ZipFile.getinfo (   self,
  name 
) [inherited]
Return the instance of ZipInfo given 'name'.

Definition at line 867 of file zipfile.py.

00867 
00868     def getinfo(self, name):
00869         """Return the instance of ZipInfo given 'name'."""
00870         info = self.NameToInfo.get(name)
00871         if info is None:
00872             raise KeyError(
00873                 'There is no item named %r in the archive' % name)
00874 
00875         return info

Here is the caller graph for this function:

def zipfile.ZipFile.infolist (   self) [inherited]
Return a list of class ZipInfo instances for files in the
archive.

Definition at line 840 of file zipfile.py.

00840 
00841     def infolist(self):
00842         """Return a list of class ZipInfo instances for files in the
00843         archive."""
00844         return self.filelist

def zipfile.ZipFile.namelist (   self) [inherited]
Return a list of file names in the archive.

Definition at line 833 of file zipfile.py.

00833 
00834     def namelist(self):
00835         """Return a list of file names in the archive."""
00836         l = []
00837         for data in self.filelist:
00838             l.append(data.filename)
00839         return l

Here is the caller graph for this function:

def zipfile.ZipFile.open (   self,
  name,
  mode = "r",
  pwd = None 
) [inherited]
Return file-like object for 'name'.

Definition at line 890 of file zipfile.py.

00890 
00891     def open(self, name, mode="r", pwd=None):
00892         """Return file-like object for 'name'."""
00893         if mode not in ("r", "U", "rU"):
00894             raise RuntimeError('open() requires mode "r", "U", or "rU"')
00895         if pwd and not isinstance(pwd, bytes):
00896             raise TypeError("pwd: expected bytes, got %s" % type(pwd))
00897         if not self.fp:
00898             raise RuntimeError(
00899                   "Attempt to read ZIP archive that was already closed")
00900 
00901         # Only open a new file for instances where we were not
00902         # given a file object in the constructor
00903         if self._filePassed:
00904             zef_file = self.fp
00905         else:
00906             zef_file = io.open(self.filename, 'rb')
00907 
00908         # Make sure we have an info object
00909         if isinstance(name, ZipInfo):
00910             # 'name' is already an info object
00911             zinfo = name
00912         else:
00913             # Get info object for name
00914             try:
00915                 zinfo = self.getinfo(name)
00916             except KeyError:
00917                 if not self._filePassed:
00918                     zef_file.close()
00919                 raise
00920         zef_file.seek(zinfo.header_offset, 0)
00921 
00922         # Skip the file header:
00923         fheader = zef_file.read(sizeFileHeader)
00924         if fheader[0:4] != stringFileHeader:
00925             raise BadZipFile("Bad magic number for file header")
00926 
00927         fheader = struct.unpack(structFileHeader, fheader)
00928         fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
00929         if fheader[_FH_EXTRA_FIELD_LENGTH]:
00930             zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
00931 
00932         if zinfo.flag_bits & 0x800:
00933             # UTF-8 filename
00934             fname_str = fname.decode("utf-8")
00935         else:
00936             fname_str = fname.decode("cp437")
00937 
00938         if fname_str != zinfo.orig_filename:
00939             if not self._filePassed:
00940                 zef_file.close()
00941             raise BadZipFile(
00942                   'File name in directory %r and header %r differ.'
00943                   % (zinfo.orig_filename, fname))
00944 
00945         # check for encrypted flag & handle password
00946         is_encrypted = zinfo.flag_bits & 0x1
00947         zd = None
00948         if is_encrypted:
00949             if not pwd:
00950                 pwd = self.pwd
00951             if not pwd:
00952                 if not self._filePassed:
00953                     zef_file.close()
00954                 raise RuntimeError("File %s is encrypted, "
00955                                    "password required for extraction" % name)
00956 
00957             zd = _ZipDecrypter(pwd)
00958             # The first 12 bytes in the cypher stream is an encryption header
00959             #  used to strengthen the algorithm. The first 11 bytes are
00960             #  completely random, while the 12th contains the MSB of the CRC,
00961             #  or the MSB of the file time depending on the header type
00962             #  and is used to check the correctness of the password.
00963             header = zef_file.read(12)
00964             h = list(map(zd, header[0:12]))
00965             if zinfo.flag_bits & 0x8:
00966                 # compare against the file type from extended local headers
00967                 check_byte = (zinfo._raw_time >> 8) & 0xff
00968             else:
00969                 # compare against the CRC otherwise
00970                 check_byte = (zinfo.CRC >> 24) & 0xff
00971             if h[11] != check_byte:
00972                 if not self._filePassed:
00973                     zef_file.close()
00974                 raise RuntimeError("Bad password for file", name)
00975 
00976         return ZipExtFile(zef_file, mode, zinfo, zd,
00977                           close_fileobj=not self._filePassed)

Here is the call graph for this function:

def zipfile.ZipFile.printdir (   self,
  file = None 
) [inherited]
Print a table of contents for the zip file.

Definition at line 845 of file zipfile.py.

00845 
00846     def printdir(self, file=None):
00847         """Print a table of contents for the zip file."""
00848         print("%-46s %19s %12s" % ("File Name", "Modified    ", "Size"),
00849               file=file)
00850         for zinfo in self.filelist:
00851             date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
00852             print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
00853                   file=file)

def zipfile.ZipFile.read (   self,
  name,
  pwd = None 
) [inherited]
Return file bytes (as a string) for name.

Definition at line 885 of file zipfile.py.

00885 
00886     def read(self, name, pwd=None):
00887         """Return file bytes (as a string) for name."""
00888         with self.open(name, "r", pwd) as fp:
00889             return fp.read()

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.ZipFile.setpassword (   self,
  pwd 
) [inherited]
Set default password for encrypted files.

Definition at line 876 of file zipfile.py.

00876 
00877     def setpassword(self, pwd):
00878         """Set default password for encrypted files."""
00879         if pwd and not isinstance(pwd, bytes):
00880             raise TypeError("pwd: expected bytes, got %s" % type(pwd))
00881         if pwd:
00882             self.pwd = pwd
00883         else:
00884             self.pwd = None

def zipfile.ZipFile.testzip (   self) [inherited]
Read all the files and check the CRC.

Definition at line 854 of file zipfile.py.

00854 
00855     def testzip(self):
00856         """Read all the files and check the CRC."""
00857         chunk_size = 2 ** 20
00858         for zinfo in self.filelist:
00859             try:
00860                 # Read by chunks, to avoid an OverflowError or a
00861                 # MemoryError with very large embedded files.
00862                 f = self.open(zinfo.filename, "r")
00863                 while f.read(chunk_size):     # Check CRC-32
00864                     pass
00865             except BadZipFile:
00866                 return zinfo.filename

Here is the call graph for this function:

def zipfile.ZipFile.write (   self,
  filename,
  arcname = None,
  compress_type = None 
) [inherited]
Put the bytes from filename into the archive under the name
arcname.

Definition at line 1064 of file zipfile.py.

01064 
01065     def write(self, filename, arcname=None, compress_type=None):
01066         """Put the bytes from filename into the archive under the name
01067         arcname."""
01068         if not self.fp:
01069             raise RuntimeError(
01070                   "Attempt to write to ZIP archive that was already closed")
01071 
01072         st = os.stat(filename)
01073         isdir = stat.S_ISDIR(st.st_mode)
01074         mtime = time.localtime(st.st_mtime)
01075         date_time = mtime[0:6]
01076         # Create ZipInfo instance to store file information
01077         if arcname is None:
01078             arcname = filename
01079         arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
01080         while arcname[0] in (os.sep, os.altsep):
01081             arcname = arcname[1:]
01082         if isdir:
01083             arcname += '/'
01084         zinfo = ZipInfo(arcname, date_time)
01085         zinfo.external_attr = (st[0] & 0xFFFF) << 16      # Unix attributes
01086         if compress_type is None:
01087             zinfo.compress_type = self.compression
01088         else:
01089             zinfo.compress_type = compress_type
01090 
01091         zinfo.file_size = st.st_size
01092         zinfo.flag_bits = 0x00
01093         zinfo.header_offset = self.fp.tell()    # Start of header bytes
01094 
01095         self._writecheck(zinfo)
01096         self._didModify = True
01097 
01098         if isdir:
01099             zinfo.file_size = 0
01100             zinfo.compress_size = 0
01101             zinfo.CRC = 0
01102             self.filelist.append(zinfo)
01103             self.NameToInfo[zinfo.filename] = zinfo
01104             self.fp.write(zinfo.FileHeader())
01105             return
01106 
01107         with open(filename, "rb") as fp:
01108             # Must overwrite CRC and sizes with correct data later
01109             zinfo.CRC = CRC = 0
01110             zinfo.compress_size = compress_size = 0
01111             zinfo.file_size = file_size = 0
01112             self.fp.write(zinfo.FileHeader())
01113             if zinfo.compress_type == ZIP_DEFLATED:
01114                 cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
01115                      zlib.DEFLATED, -15)
01116             else:
01117                 cmpr = None
01118             while 1:
01119                 buf = fp.read(1024 * 8)
01120                 if not buf:
01121                     break
01122                 file_size = file_size + len(buf)
01123                 CRC = crc32(buf, CRC) & 0xffffffff
01124                 if cmpr:
01125                     buf = cmpr.compress(buf)
01126                     compress_size = compress_size + len(buf)
01127                 self.fp.write(buf)
01128         if cmpr:
01129             buf = cmpr.flush()
01130             compress_size = compress_size + len(buf)
01131             self.fp.write(buf)
01132             zinfo.compress_size = compress_size
01133         else:
01134             zinfo.compress_size = file_size
01135         zinfo.CRC = CRC
01136         zinfo.file_size = file_size
01137         # Seek backwards and write CRC and file sizes
01138         position = self.fp.tell()       # Preserve current position in file
01139         self.fp.seek(zinfo.header_offset + 14, 0)
01140         self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size,
01141               zinfo.file_size))
01142         self.fp.seek(position, 0)
01143         self.filelist.append(zinfo)
01144         self.NameToInfo[zinfo.filename] = zinfo

Here is the call graph for this function:

def zipfile.PyZipFile.writepy (   self,
  pathname,
  basename = "" 
)
Add all files from "pathname" to the ZIP archive.

If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive.  If pathname is a plain
directory, listdir *.py and enter all modules.  Else, pathname
must be a Python *.py file and the module will be put into the
archive.  Added modules are always module.pyo or module.pyc.
This method will compile the module.py into module.pyc if
necessary.

Definition at line 1314 of file zipfile.py.

01314 
01315     def writepy(self, pathname, basename=""):
01316         """Add all files from "pathname" to the ZIP archive.
01317 
01318         If pathname is a package directory, search the directory and
01319         all package subdirectories recursively for all *.py and enter
01320         the modules into the archive.  If pathname is a plain
01321         directory, listdir *.py and enter all modules.  Else, pathname
01322         must be a Python *.py file and the module will be put into the
01323         archive.  Added modules are always module.pyo or module.pyc.
01324         This method will compile the module.py into module.pyc if
01325         necessary.
01326         """
01327         dir, name = os.path.split(pathname)
01328         if os.path.isdir(pathname):
01329             initname = os.path.join(pathname, "__init__.py")
01330             if os.path.isfile(initname):
01331                 # This is a package directory, add it
01332                 if basename:
01333                     basename = "%s/%s" % (basename, name)
01334                 else:
01335                     basename = name
01336                 if self.debug:
01337                     print("Adding package in", pathname, "as", basename)
01338                 fname, arcname = self._get_codename(initname[0:-3], basename)
01339                 if self.debug:
01340                     print("Adding", arcname)
01341                 self.write(fname, arcname)
01342                 dirlist = os.listdir(pathname)
01343                 dirlist.remove("__init__.py")
01344                 # Add all *.py files and package subdirectories
01345                 for filename in dirlist:
01346                     path = os.path.join(pathname, filename)
01347                     root, ext = os.path.splitext(filename)
01348                     if os.path.isdir(path):
01349                         if os.path.isfile(os.path.join(path, "__init__.py")):
01350                             # This is a package directory, add it
01351                             self.writepy(path, basename)  # Recursive call
01352                     elif ext == ".py":
01353                         fname, arcname = self._get_codename(path[0:-3],
01354                                          basename)
01355                         if self.debug:
01356                             print("Adding", arcname)
01357                         self.write(fname, arcname)
01358             else:
01359                 # This is NOT a package directory, add its files at top level
01360                 if self.debug:
01361                     print("Adding files from directory", pathname)
01362                 for filename in os.listdir(pathname):
01363                     path = os.path.join(pathname, filename)
01364                     root, ext = os.path.splitext(filename)
01365                     if ext == ".py":
01366                         fname, arcname = self._get_codename(path[0:-3],
01367                                          basename)
01368                         if self.debug:
01369                             print("Adding", arcname)
01370                         self.write(fname, arcname)
01371         else:
01372             if pathname[-3:] != ".py":
01373                 raise RuntimeError(
01374                       'Files added with writepy() must end with ".py"')
01375             fname, arcname = self._get_codename(pathname[0:-3], basename)
01376             if self.debug:
01377                 print("Adding file", arcname)
01378             self.write(fname, arcname)

Here is the caller graph for this function:

def zipfile.ZipFile.writestr (   self,
  zinfo_or_arcname,
  data,
  compress_type = None 
) [inherited]
Write a file into the archive.  The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive.

Definition at line 1145 of file zipfile.py.

01145 
01146     def writestr(self, zinfo_or_arcname, data, compress_type=None):
01147         """Write a file into the archive.  The contents is 'data', which
01148         may be either a 'str' or a 'bytes' instance; if it is a 'str',
01149         it is encoded as UTF-8 first.
01150         'zinfo_or_arcname' is either a ZipInfo instance or
01151         the name of the file in the archive."""
01152         if isinstance(data, str):
01153             data = data.encode("utf-8")
01154         if not isinstance(zinfo_or_arcname, ZipInfo):
01155             zinfo = ZipInfo(filename=zinfo_or_arcname,
01156                             date_time=time.localtime(time.time())[:6])
01157             zinfo.compress_type = self.compression
01158             zinfo.external_attr = 0o600 << 16
01159         else:
01160             zinfo = zinfo_or_arcname
01161 
01162         if not self.fp:
01163             raise RuntimeError(
01164                   "Attempt to write to ZIP archive that was already closed")
01165 
01166         zinfo.file_size = len(data)            # Uncompressed size
01167         zinfo.header_offset = self.fp.tell()    # Start of header data
01168         if compress_type is not None:
01169             zinfo.compress_type = compress_type
01170 
01171         self._writecheck(zinfo)
01172         self._didModify = True
01173         zinfo.CRC = crc32(data) & 0xffffffff       # CRC-32 checksum
01174         if zinfo.compress_type == ZIP_DEFLATED:
01175             co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
01176                  zlib.DEFLATED, -15)
01177             data = co.compress(data) + co.flush()
01178             zinfo.compress_size = len(data)    # Compressed size
01179         else:
01180             zinfo.compress_size = zinfo.file_size
01181         zinfo.header_offset = self.fp.tell()    # Start of header data
01182         self.fp.write(zinfo.FileHeader())
01183         self.fp.write(data)
01184         self.fp.flush()
01185         if zinfo.flag_bits & 0x08:
01186             # Write CRC and file sizes after the file data
01187             self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size,
01188                   zinfo.file_size))
01189         self.filelist.append(zinfo)
01190         self.NameToInfo[zinfo.filename] = zinfo

Here is the call graph for this function:


Member Data Documentation

Definition at line 1312 of file zipfile.py.

Definition at line 697 of file zipfile.py.

Definition at line 694 of file zipfile.py.

zipfile.ZipFile.debug [inherited]

Definition at line 691 of file zipfile.py.

Definition at line 693 of file zipfile.py.

Definition at line 703 of file zipfile.py.

zipfile.ZipFile.fp = None [static, inherited]

Definition at line 673 of file zipfile.py.

zipfile.ZipFile.mode [inherited]

Definition at line 695 of file zipfile.py.

Definition at line 692 of file zipfile.py.

zipfile.ZipFile.pwd [inherited]

Definition at line 696 of file zipfile.py.

Definition at line 785 of file zipfile.py.


The documentation for this class was generated from the following file: