Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
ZipFile Class Reference
Inheritance diagram for ZipFile:
PyZipFile

Public Member Functions

def __init__
 
def namelist
 
def infolist
 
def printdir
 
def testzip
 
def getinfo
 
def read
 
def write
 
def writestr
 
def __del__
 
def close
 

Data Fields

 debug
 
 NameToInfo
 
 filelist
 
 compression
 
 mode
 
 filename
 
 start_dir
 

Static Public Attributes

 fp = None
 

Detailed Description

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

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

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).

Definition at line 147 of file zipfile.py.

Constructor & Destructor Documentation

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

Definition at line 160 of file zipfile.py.

161  def __init__(self, file, mode="r", compression=ZIP_STORED):
162  """Open the ZIP file with mode read "r", write "w" or append "a"."""
163  if compression == ZIP_STORED:
164  pass
165  elif compression == ZIP_DEFLATED:
166  if not zlib:
167  raise RuntimeError,\
168  "Compression requires the (missing) zlib module"
169  else:
170  raise RuntimeError, "That compression method is not supported"
171  self.debug = 0 # Level of printing: 0 through 3
172  self.NameToInfo = {} # Find file info given name
173  self.filelist = [] # List of ZipInfo instances for archive
174  self.compression = compression # Method of compression
175  self.mode = key = mode[0]
176 
177  # Check if we were passed a file-like object
178  if type(file) in _STRING_TYPES:
179  self._filePassed = 0
180  self.filename = file
181  modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
182  self.fp = open(file, modeDict[mode])
183  else:
184  self._filePassed = 1
185  self.fp = file
186  self.filename = getattr(file, 'name', None)
187 
188  if key == 'r':
189  self._GetContents()
190  elif key == 'w':
191  pass
192  elif key == 'a':
193  fp = self.fp
194  fp.seek(-22, 2) # Seek to end-of-file record
195  endrec = fp.read()
196  if endrec[0:4] == stringEndArchive and \
197  endrec[-2:] == "\000\000":
198  self._GetContents() # file is a zip file
199  # seek to start of directory and overwrite
200  fp.seek(self.start_dir, 0)
201  else: # file is not a zip file, just append
202  fp.seek(0, 2)
203  else:
204  if not self._filePassed:
205  self.fp.close()
206  self.fp = None
207  raise RuntimeError, 'Mode must be "r", "w" or "a"'
def __del__ (   self)

Member Function Documentation

def close (   self)
Close the file, and for mode "w" and "a" write the ending
records.

Definition at line 459 of file zipfile.py.

References ZipFile._filePassed, ZipFile.filelist, _Mailbox.fp, _Subfile.fp, MultiFile.fp, Message.fp, HTTPResponse.fp, ZipFile.fp, HTTPError.fp, FieldStorage.fp, addbase.fp, GzipFile.mode, and ZipFile.mode.

460  def close(self):
461  """Close the file, and for mode "w" and "a" write the ending
462  records."""
463  if self.fp is None:
464  return
465  if self.mode in ("w", "a"): # write ending records
466  count = 0
467  pos1 = self.fp.tell()
468  for zinfo in self.filelist: # write central directory
469  count = count + 1
470  dt = zinfo.date_time
471  dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
472  dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
473  centdir = struct.pack(structCentralDir,
474  stringCentralDir, zinfo.create_version,
475  zinfo.create_system, zinfo.extract_version, zinfo.reserved,
476  zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
477  zinfo.CRC, zinfo.compress_size, zinfo.file_size,
478  len(zinfo.filename), len(zinfo.extra), len(zinfo.comment),
479  0, zinfo.internal_attr, zinfo.external_attr,
480  zinfo.header_offset)
481  self.fp.write(centdir)
482  self.fp.write(zinfo.filename)
483  self.fp.write(zinfo.extra)
484  self.fp.write(zinfo.comment)
485  pos2 = self.fp.tell()
486  # Write end-of-zip-archive record
487  endrec = struct.pack(structEndArchive, stringEndArchive,
488  0, 0, count, count, pos2 - pos1, pos1, 0)
489  self.fp.write(endrec)
490  self.fp.flush()
491  if not self._filePassed:
492  self.fp.close()
493  self.fp = None
494 
def getinfo (   self,
  name 
)
Return the instance of ZipInfo given 'name'.

Definition at line 316 of file zipfile.py.

References ZipFile.NameToInfo.

317  def getinfo(self, name):
318  """Return the instance of ZipInfo given 'name'."""
319  return self.NameToInfo[name]
def infolist (   self)
Return a list of class ZipInfo instances for files in the
archive.

Definition at line 296 of file zipfile.py.

References ZipFile.filelist.

297  def infolist(self):
298  """Return a list of class ZipInfo instances for files in the
299  archive."""
300  return self.filelist
def namelist (   self)
Return a list of file names in the archive.

Definition at line 289 of file zipfile.py.

References ZipFile.filelist.

290  def namelist(self):
291  """Return a list of file names in the archive."""
292  l = []
293  for data in self.filelist:
294  l.append(data.filename)
295  return l
def printdir (   self)
Print a table of contents for the zip file.

Definition at line 301 of file zipfile.py.

References ZipFile.filelist.

302  def printdir(self):
303  """Print a table of contents for the zip file."""
304  print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
305  for zinfo in self.filelist:
306  date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time
307  print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
def read (   self,
  name 
)
Return file bytes (as a string) for name.

Definition at line 320 of file zipfile.py.

References shlex.debug, FTP.debug, ZipFile.debug, NNTP.debug, dispatcher.debug, _Mailbox.fp, _Subfile.fp, MultiFile.fp, Message.fp, HTTPResponse.fp, ZipFile.fp, HTTPError.fp, FieldStorage.fp, addbase.fp, ZipFile.getinfo(), GzipFile.mode, and ZipFile.mode.

321  def read(self, name):
322  """Return file bytes (as a string) for name."""
323  if self.mode not in ("r", "a"):
324  raise RuntimeError, 'read() requires mode "r" or "a"'
325  if not self.fp:
326  raise RuntimeError, \
327  "Attempt to read ZIP archive that was already closed"
328  zinfo = self.getinfo(name)
329  filepos = self.fp.tell()
330  self.fp.seek(zinfo.file_offset, 0)
331  bytes = self.fp.read(zinfo.compress_size)
332  self.fp.seek(filepos, 0)
333  if zinfo.compress_type == ZIP_STORED:
334  pass
335  elif zinfo.compress_type == ZIP_DEFLATED:
336  if not zlib:
337  raise RuntimeError, \
338  "De-compression requires the (missing) zlib module"
339  # zlib compress/decompress code by Jeremy Hylton of CNRI
340  dc = zlib.decompressobj(-15)
341  bytes = dc.decompress(bytes)
342  # need to feed in unused pad byte so that zlib won't choke
343  ex = dc.decompress('Z') + dc.flush()
344  if ex:
345  bytes = bytes + ex
346  else:
347  raise BadZipfile, \
348  "Unsupported compression method %d for file %s" % \
349  (zinfo.compress_type, name)
350  crc = binascii.crc32(bytes)
351  if crc != zinfo.CRC:
352  raise BadZipfile, "Bad CRC-32 for file %s" % name
353  return bytes
def testzip (   self)
Read all the files and check the CRC.

Definition at line 308 of file zipfile.py.

References ZipFile.filelist, RobotFileParser.read(), _Subfile.read(), StringIO.read(), openrsrc.read(), Chunk.read(), MultiFile.read(), MimeTypes.read(), GzipFile.read(), StreamReader.read(), _fileobject.read(), ConfigParser.read(), HTTPResponse.read(), _Hqxdecoderengine.read(), ZipFile.read(), StreamReaderWriter.read(), _Rledecoderengine.read(), StreamRecoder.read(), HexBin.read(), file_wrapper.read, Unpickler.read, and addbase.read.

309  def testzip(self):
310  """Read all the files and check the CRC."""
311  for zinfo in self.filelist:
312  try:
313  self.read(zinfo.filename) # Check CRC-32
314  except:
315  return zinfo.filename
def write (   self,
  filename,
  arcname = None,
  compress_type = None 
)
Put the bytes from filename into the archive under the name
arcname.

Definition at line 371 of file zipfile.py.

References ZipFile._writecheck(), ZipFile.compression, ZipFile.NameToInfo, and aifc.open().

372  def write(self, filename, arcname=None, compress_type=None):
373  """Put the bytes from filename into the archive under the name
374  arcname."""
375  st = os.stat(filename)
376  mtime = time.localtime(st[8])
377  date_time = mtime[0:6]
378  # Create ZipInfo instance to store file information
379  if arcname is None:
380  zinfo = ZipInfo(filename, date_time)
381  else:
382  zinfo = ZipInfo(arcname, date_time)
383  zinfo.external_attr = st[0] << 16 # Unix attributes
384  if compress_type is None:
385  zinfo.compress_type = self.compression
386  else:
387  zinfo.compress_type = compress_type
388  self._writecheck(zinfo)
389  fp = open(filename, "rb")
390  zinfo.flag_bits = 0x00
391  zinfo.header_offset = self.fp.tell() # Start of header bytes
392  # Must overwrite CRC and sizes with correct data later
393  zinfo.CRC = CRC = 0
394  zinfo.compress_size = compress_size = 0
395  zinfo.file_size = file_size = 0
396  self.fp.write(zinfo.FileHeader())
397  zinfo.file_offset = self.fp.tell() # Start of file bytes
398  if zinfo.compress_type == ZIP_DEFLATED:
399  cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
400  zlib.DEFLATED, -15)
401  else:
402  cmpr = None
403  while 1:
404  buf = fp.read(1024 * 8)
405  if not buf:
406  break
407  file_size = file_size + len(buf)
408  CRC = binascii.crc32(buf, CRC)
409  if cmpr:
410  buf = cmpr.compress(buf)
411  compress_size = compress_size + len(buf)
412  self.fp.write(buf)
413  fp.close()
414  if cmpr:
415  buf = cmpr.flush()
416  compress_size = compress_size + len(buf)
417  self.fp.write(buf)
418  zinfo.compress_size = compress_size
419  else:
420  zinfo.compress_size = file_size
421  zinfo.CRC = CRC
422  zinfo.file_size = file_size
423  # Seek backwards and write CRC and file sizes
424  position = self.fp.tell() # Preserve current position in file
425  self.fp.seek(zinfo.header_offset + 14, 0)
426  self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size,
427  zinfo.file_size))
428  self.fp.seek(position, 0)
429  self.filelist.append(zinfo)
430  self.NameToInfo[zinfo.filename] = zinfo
def writestr (   self,
  zinfo,
  bytes 
)
Write a file into the archive.  The contents is the string
'bytes'.

Definition at line 431 of file zipfile.py.

References ZipFile._writecheck(), and ZipFile.NameToInfo.

432  def writestr(self, zinfo, bytes):
433  """Write a file into the archive. The contents is the string
434  'bytes'."""
435  self._writecheck(zinfo)
436  zinfo.file_size = len(bytes) # Uncompressed size
437  zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum
438  if zinfo.compress_type == ZIP_DEFLATED:
439  co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
440  zlib.DEFLATED, -15)
441  bytes = co.compress(bytes) + co.flush()
442  zinfo.compress_size = len(bytes) # Compressed size
443  else:
444  zinfo.compress_size = zinfo.file_size
445  zinfo.header_offset = self.fp.tell() # Start of header bytes
446  self.fp.write(zinfo.FileHeader())
447  zinfo.file_offset = self.fp.tell() # Start of file bytes
448  self.fp.write(bytes)
449  if zinfo.flag_bits & 0x08:
450  # Write CRC and file sizes after the file data
451  self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size,
452  zinfo.file_size))
453  self.filelist.append(zinfo)
454  self.NameToInfo[zinfo.filename] = zinfo

Field Documentation

compression

Definition at line 173 of file zipfile.py.

debug

Definition at line 170 of file zipfile.py.

filelist

Definition at line 172 of file zipfile.py.

filename

Definition at line 179 of file zipfile.py.

fp = None
static

Definition at line 158 of file zipfile.py.

mode

Definition at line 174 of file zipfile.py.

NameToInfo

Definition at line 171 of file zipfile.py.

start_dir

Definition at line 238 of file zipfile.py.


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