Back to index

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

List of all members.

Public Member Functions

def __init__
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 __del__
def close

Public Attributes

 debug
 NameToInfo
 filelist
 compression
 mode
 pwd
 comment
 filename
 start_dir

Static Public Attributes

 fp = None

Private Member Functions

def _GetContents
def _RealGetContents
def _extract_member
def _writecheck

Private Attributes

 _allowZip64
 _didModify
 _filePassed

Detailed Description

Class with methods to open, read, write, close, list zip files.

z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=False)

file: Either the path to the file, or a file-like object.
      If it is a path, the file will be opened and closed by ZipFile.
mode: The mode can be either read "r", write "w" or append "a".
compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib).
allowZip64: if True ZipFile will create files with ZIP64 extensions when
            needed, otherwise it will raise an exception when this would
            be necessary.

Definition at line 658 of file zipfile.py.


Constructor & Destructor Documentation

def zipfile.ZipFile.__init__ (   self,
  file,
  mode = "r",
  compression = ZIP_STORED,
  allowZip64 = False 
)
Open the ZIP file with mode read "r", write "w" or append "a".

Definition at line 675 of file zipfile.py.

00675 
00676     def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False):
00677         """Open the ZIP file with mode read "r", write "w" or append "a"."""
00678         if mode not in ("r", "w", "a"):
00679             raise RuntimeError('ZipFile() requires mode "r", "w", or "a"')
00680 
00681         if compression == ZIP_STORED:
00682             pass
00683         elif compression == ZIP_DEFLATED:
00684             if not zlib:
00685                 raise RuntimeError(
00686                       "Compression requires the (missing) zlib module")
00687         else:
00688             raise RuntimeError("That compression method is not supported")
00689 
00690         self._allowZip64 = allowZip64
00691         self._didModify = False
00692         self.debug = 0  # Level of printing: 0 through 3
00693         self.NameToInfo = {}    # Find file info given name
00694         self.filelist = []      # List of ZipInfo instances for archive
00695         self.compression = compression  # Method of compression
00696         self.mode = key = mode.replace('b', '')[0]
00697         self.pwd = None
00698         self.comment = b''
00699 
00700         # Check if we were passed a file-like object
00701         if isinstance(file, str):
00702             # No, it's a filename
00703             self._filePassed = 0
00704             self.filename = file
00705             modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
00706             try:
00707                 self.fp = io.open(file, modeDict[mode])
00708             except IOError:
00709                 if mode == 'a':
00710                     mode = key = 'w'
00711                     self.fp = io.open(file, modeDict[mode])
00712                 else:
00713                     raise
00714         else:
00715             self._filePassed = 1
00716             self.fp = file
00717             self.filename = getattr(file, 'name', None)
00718 
00719         if key == 'r':
00720             self._GetContents()
00721         elif key == 'w':
00722             # set the modified flag so central directory gets written
00723             # even if no files are added to the archive
00724             self._didModify = True
00725         elif key == 'a':
00726             try:
00727                 # See if file is a zip file
00728                 self._RealGetContents()
00729                 # seek to start of directory and overwrite
00730                 self.fp.seek(self.start_dir, 0)
00731             except BadZipFile:
00732                 # file is not a zip file, just append
00733                 self.fp.seek(0, 2)
00734 
00735                 # set the modified flag so central directory gets written
00736                 # even if no files are added to the archive
00737                 self._didModify = True
00738         else:
00739             if not self._filePassed:
00740                 self.fp.close()
00741                 self.fp = None
00742             raise RuntimeError('Mode must be "r", "w" or "a"')

Here is the caller graph for this function:

def zipfile.ZipFile.__del__ (   self)
Call the "close()" method in case the user forgot.

Definition at line 1191 of file zipfile.py.

01191 
01192     def __del__(self):
01193         """Call the "close()" method in case the user forgot."""
01194         self.close()


Member Function Documentation

def zipfile.ZipFile.__enter__ (   self)

Definition at line 743 of file zipfile.py.

00743 
00744     def __enter__(self):
00745         return self

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

Definition at line 746 of file zipfile.py.

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

def zipfile.ZipFile._extract_member (   self,
  member,
  targetpath,
  pwd 
) [private]
Extract the ZipInfo object 'member' to a physical
   file on the path targetpath.

Definition at line 1004 of file zipfile.py.

01004 
01005     def _extract_member(self, member, targetpath, pwd):
01006         """Extract the ZipInfo object 'member' to a physical
01007            file on the path targetpath.
01008         """
01009         # build the destination pathname, replacing
01010         # forward slashes to platform specific separators.
01011         # Strip trailing path separator, unless it represents the root.
01012         if (targetpath[-1:] in (os.path.sep, os.path.altsep)
01013             and len(os.path.splitdrive(targetpath)[1]) > 1):
01014             targetpath = targetpath[:-1]
01015 
01016         # don't include leading "/" from file name if present
01017         if member.filename[0] == '/':
01018             targetpath = os.path.join(targetpath, member.filename[1:])
01019         else:
01020             targetpath = os.path.join(targetpath, member.filename)
01021 
01022         targetpath = os.path.normpath(targetpath)
01023 
01024         # Create all upper directories if necessary.
01025         upperdirs = os.path.dirname(targetpath)
01026         if upperdirs and not os.path.exists(upperdirs):
01027             os.makedirs(upperdirs)
01028 
01029         if member.filename[-1] == '/':
01030             if not os.path.isdir(targetpath):
01031                 os.mkdir(targetpath)
01032             return targetpath
01033 
01034         source = self.open(member, pwd=pwd)
01035         target = open(targetpath, "wb")
01036         shutil.copyfileobj(source, target)
01037         source.close()
01038         target.close()
01039 
01040         return targetpath

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.ZipFile._GetContents (   self) [private]
Read the directory, making sure we close the file if the format
is bad.

Definition at line 749 of file zipfile.py.

00749 
00750     def _GetContents(self):
00751         """Read the directory, making sure we close the file if the format
00752         is bad."""
00753         try:
00754             self._RealGetContents()
00755         except BadZipFile:
00756             if not self._filePassed:
00757                 self.fp.close()
00758                 self.fp = None
00759             raise

Here is the call graph for this function:

def zipfile.ZipFile._RealGetContents (   self) [private]
Read in the table of contents for the ZIP file.

Definition at line 760 of file zipfile.py.

00760 
00761     def _RealGetContents(self):
00762         """Read in the table of contents for the ZIP file."""
00763         fp = self.fp
00764         try:
00765             endrec = _EndRecData(fp)
00766         except IOError:
00767             raise BadZipFile("File is not a zip file")
00768         if not endrec:
00769             raise BadZipFile("File is not a zip file")
00770         if self.debug > 1:
00771             print(endrec)
00772         size_cd = endrec[_ECD_SIZE]             # bytes in central directory
00773         offset_cd = endrec[_ECD_OFFSET]         # offset of central directory
00774         self.comment = endrec[_ECD_COMMENT]     # archive comment
00775 
00776         # "concat" is zero, unless zip was concatenated to another file
00777         concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
00778         if endrec[_ECD_SIGNATURE] == stringEndArchive64:
00779             # If Zip64 extension structures are present, account for them
00780             concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
00781 
00782         if self.debug > 2:
00783             inferred = concat + offset_cd
00784             print("given, inferred, offset", offset_cd, inferred, concat)
00785         # self.start_dir:  Position of start of central directory
00786         self.start_dir = offset_cd + concat
00787         fp.seek(self.start_dir, 0)
00788         data = fp.read(size_cd)
00789         fp = io.BytesIO(data)
00790         total = 0
00791         while total < size_cd:
00792             centdir = fp.read(sizeCentralDir)
00793             if centdir[0:4] != stringCentralDir:
00794                 raise BadZipFile("Bad magic number for central directory")
00795             centdir = struct.unpack(structCentralDir, centdir)
00796             if self.debug > 2:
00797                 print(centdir)
00798             filename = fp.read(centdir[_CD_FILENAME_LENGTH])
00799             flags = centdir[5]
00800             if flags & 0x800:
00801                 # UTF-8 file names extension
00802                 filename = filename.decode('utf-8')
00803             else:
00804                 # Historical ZIP filename encoding
00805                 filename = filename.decode('cp437')
00806             # Create ZipInfo instance to store file information
00807             x = ZipInfo(filename)
00808             x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
00809             x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
00810             x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
00811             (x.create_version, x.create_system, x.extract_version, x.reserved,
00812                 x.flag_bits, x.compress_type, t, d,
00813                 x.CRC, x.compress_size, x.file_size) = centdir[1:12]
00814             x.volume, x.internal_attr, x.external_attr = centdir[15:18]
00815             # Convert date/time code to (year, month, day, hour, min, sec)
00816             x._raw_time = t
00817             x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
00818                                      t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
00819 
00820             x._decodeExtra()
00821             x.header_offset = x.header_offset + concat
00822             self.filelist.append(x)
00823             self.NameToInfo[x.filename] = x
00824 
00825             # update total bytes read from central directory
00826             total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
00827                      + centdir[_CD_EXTRA_FIELD_LENGTH]
00828                      + centdir[_CD_COMMENT_LENGTH])
00829 
00830             if self.debug > 2:
00831                 print("total", total)
00832 

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.ZipFile._writecheck (   self,
  zinfo 
) [private]
Check for errors before writing a file to the archive.

Definition at line 1041 of file zipfile.py.

01041 
01042     def _writecheck(self, zinfo):
01043         """Check for errors before writing a file to the archive."""
01044         if zinfo.filename in self.NameToInfo:
01045             if self.debug:      # Warning for duplicate names
01046                 print("Duplicate name:", zinfo.filename)
01047         if self.mode not in ("w", "a"):
01048             raise RuntimeError('write() requires mode "w" or "a"')
01049         if not self.fp:
01050             raise RuntimeError(
01051                   "Attempt to write ZIP archive that was already closed")
01052         if zinfo.compress_type == ZIP_DEFLATED and not zlib:
01053             raise RuntimeError(
01054                   "Compression requires the (missing) zlib module")
01055         if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
01056             raise RuntimeError("That compression method is not supported")
01057         if zinfo.file_size > ZIP64_LIMIT:
01058             if not self._allowZip64:
01059                 raise LargeZipFile("Filesize would require ZIP64 extensions")
01060         if zinfo.header_offset > ZIP64_LIMIT:
01061             if not self._allowZip64:
01062                 raise LargeZipFile(
01063                       "Zipfile size would require ZIP64 extensions")

Here is the caller graph for this function:

def zipfile.ZipFile.close (   self)
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 
)
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 
)
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 
)
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)
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)
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 
)
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 
)
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 
)
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 
)
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)
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 
)
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.ZipFile.writestr (   self,
  zinfo_or_arcname,
  data,
  compress_type = None 
)
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 689 of file zipfile.py.

Definition at line 690 of file zipfile.py.

Definition at line 702 of file zipfile.py.

Definition at line 697 of file zipfile.py.

Definition at line 694 of file zipfile.py.

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]

Definition at line 673 of file zipfile.py.

Definition at line 695 of file zipfile.py.

Definition at line 692 of file zipfile.py.

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: