Back to index

python3.2  3.2.2
Classes | Functions | Variables
zipfile Namespace Reference

Classes

class  BadZipFile
class  LargeZipFile
class  ZipInfo
class  _ZipDecrypter
class  ZipExtFile
class  ZipFile
class  PyZipFile

Functions

def _check_zipfile
def is_zipfile
def _EndRecData64
def _EndRecData
def main

Variables

 crc32 = zlib.crc32
 zlib = None
list __all__
 error = BadZipfileBadZipFile
tuple ZIP64_LIMIT = (1 << 31)
int ZIP_FILECOUNT_LIMIT = 1
tuple ZIP_MAX_COMMENT = (1 << 16)
int ZIP_STORED = 0
int ZIP_DEFLATED = 8
string structEndArchive = "<4s4H2LH"
string stringEndArchive = "PK\005\006"
tuple sizeEndCentDir = struct.calcsize(structEndArchive)
int _ECD_SIGNATURE = 0
int _ECD_DISK_NUMBER = 1
int _ECD_DISK_START = 2
int _ECD_ENTRIES_THIS_DISK = 3
int _ECD_ENTRIES_TOTAL = 4
int _ECD_SIZE = 5
int _ECD_OFFSET = 6
int _ECD_COMMENT_SIZE = 7
int _ECD_COMMENT = 8
int _ECD_LOCATION = 9
string structCentralDir = "<4s4B4HL2L5H2L"
string stringCentralDir = "PK\001\002"
tuple sizeCentralDir = struct.calcsize(structCentralDir)
int _CD_SIGNATURE = 0
int _CD_CREATE_VERSION = 1
int _CD_CREATE_SYSTEM = 2
int _CD_EXTRACT_VERSION = 3
int _CD_EXTRACT_SYSTEM = 4
int _CD_FLAG_BITS = 5
int _CD_COMPRESS_TYPE = 6
int _CD_TIME = 7
int _CD_DATE = 8
int _CD_CRC = 9
int _CD_COMPRESSED_SIZE = 10
int _CD_UNCOMPRESSED_SIZE = 11
int _CD_FILENAME_LENGTH = 12
int _CD_EXTRA_FIELD_LENGTH = 13
int _CD_COMMENT_LENGTH = 14
int _CD_DISK_NUMBER_START = 15
int _CD_INTERNAL_FILE_ATTRIBUTES = 16
int _CD_EXTERNAL_FILE_ATTRIBUTES = 17
int _CD_LOCAL_HEADER_OFFSET = 18
string structFileHeader = "<4s2B4HL2L2H"
string stringFileHeader = "PK\003\004"
tuple sizeFileHeader = struct.calcsize(structFileHeader)
int _FH_SIGNATURE = 0
int _FH_EXTRACT_VERSION = 1
int _FH_EXTRACT_SYSTEM = 2
int _FH_GENERAL_PURPOSE_FLAG_BITS = 3
int _FH_COMPRESSION_METHOD = 4
int _FH_LAST_MOD_TIME = 5
int _FH_LAST_MOD_DATE = 6
int _FH_CRC = 7
int _FH_COMPRESSED_SIZE = 8
int _FH_UNCOMPRESSED_SIZE = 9
int _FH_FILENAME_LENGTH = 10
int _FH_EXTRA_FIELD_LENGTH = 11
string structEndArchive64Locator = "<4sLQL"
string stringEndArchive64Locator = "PK\x06\x07"
tuple sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
string structEndArchive64 = "<4sQ2H2L4Q"
string stringEndArchive64 = "PK\x06\x06"
tuple sizeEndCentDir64 = struct.calcsize(structEndArchive64)
int _CD64_SIGNATURE = 0
int _CD64_DIRECTORY_RECSIZE = 1
int _CD64_CREATE_VERSION = 2
int _CD64_EXTRACT_VERSION = 3
int _CD64_DISK_NUMBER = 4
int _CD64_DISK_NUMBER_START = 5
int _CD64_NUMBER_ENTRIES_THIS_DISK = 6
int _CD64_NUMBER_ENTRIES_TOTAL = 7
int _CD64_DIRECTORY_SIZE = 8
int _CD64_OFFSET_START_CENTDIR = 9

Detailed Description

Read and write ZIP files.

XXX references to utf-8 need further investigation.

Function Documentation

def zipfile._check_zipfile (   fp) [private]

Definition at line 143 of file zipfile.py.

00143 
00144 def _check_zipfile(fp):
00145     try:
00146         if _EndRecData(fp):
00147             return True         # file has correct magic number
00148     except IOError:
00149         pass
00150     return False

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile._EndRecData (   fpin) [private]
Return data from the "End of Central Directory" record, or None.

The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record.

Definition at line 206 of file zipfile.py.

00206 
00207 def _EndRecData(fpin):
00208     """Return data from the "End of Central Directory" record, or None.
00209 
00210     The data is a list of the nine items in the ZIP "End of central dir"
00211     record followed by a tenth item, the file seek offset of this record."""
00212 
00213     # Determine file size
00214     fpin.seek(0, 2)
00215     filesize = fpin.tell()
00216 
00217     # Check to see if this is ZIP file with no archive comment (the
00218     # "end of central directory" structure should be the last item in the
00219     # file if this is the case).
00220     try:
00221         fpin.seek(-sizeEndCentDir, 2)
00222     except IOError:
00223         return None
00224     data = fpin.read()
00225     if data[0:4] == stringEndArchive and data[-2:] == b"\000\000":
00226         # the signature is correct and there's no comment, unpack structure
00227         endrec = struct.unpack(structEndArchive, data)
00228         endrec=list(endrec)
00229 
00230         # Append a blank comment and record start offset
00231         endrec.append(b"")
00232         endrec.append(filesize - sizeEndCentDir)
00233 
00234         # Try to read the "Zip64 end of central directory" structure
00235         return _EndRecData64(fpin, -sizeEndCentDir, endrec)
00236 
00237     # Either this is not a ZIP file, or it is a ZIP file with an archive
00238     # comment.  Search the end of the file for the "end of central directory"
00239     # record signature. The comment is the last item in the ZIP file and may be
00240     # up to 64K long.  It is assumed that the "end of central directory" magic
00241     # number does not appear in the comment.
00242     maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
00243     fpin.seek(maxCommentStart, 0)
00244     data = fpin.read()
00245     start = data.rfind(stringEndArchive)
00246     if start >= 0:
00247         # found the magic number; attempt to unpack and interpret
00248         recData = data[start:start+sizeEndCentDir]
00249         endrec = list(struct.unpack(structEndArchive, recData))
00250         commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
00251         comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
00252         endrec.append(comment)
00253         endrec.append(maxCommentStart + start)
00254 
00255         # Try to read the "Zip64 end of central directory" structure
00256         return _EndRecData64(fpin, maxCommentStart + start - filesize,
00257                              endrec)
00258 
00259     # Unable to find a valid end of central directory structure
00260     return
00261 

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile._EndRecData64 (   fpin,
  offset,
  endrec 
) [private]
Read the ZIP64 end-of-archive records and use that to update endrec

Definition at line 167 of file zipfile.py.

00167 
00168 def _EndRecData64(fpin, offset, endrec):
00169     """
00170     Read the ZIP64 end-of-archive records and use that to update endrec
00171     """
00172     try:
00173         fpin.seek(offset - sizeEndCentDir64Locator, 2)
00174     except IOError:
00175         # If the seek fails, the file is not large enough to contain a ZIP64
00176         # end-of-archive record, so just return the end record we were given.
00177         return endrec
00178 
00179     data = fpin.read(sizeEndCentDir64Locator)
00180     sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
00181     if sig != stringEndArchive64Locator:
00182         return endrec
00183 
00184     if diskno != 0 or disks != 1:
00185         raise BadZipFile("zipfiles that span multiple disks are not supported")
00186 
00187     # Assume no 'zip64 extensible data'
00188     fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
00189     data = fpin.read(sizeEndCentDir64)
00190     sig, sz, create_version, read_version, disk_num, disk_dir, \
00191             dircount, dircount2, dirsize, diroffset = \
00192             struct.unpack(structEndArchive64, data)
00193     if sig != stringEndArchive64:
00194         return endrec
00195 
00196     # Update the original endrec using data from the ZIP64 record
00197     endrec[_ECD_SIGNATURE] = sig
00198     endrec[_ECD_DISK_NUMBER] = disk_num
00199     endrec[_ECD_DISK_START] = disk_dir
00200     endrec[_ECD_ENTRIES_THIS_DISK] = dircount
00201     endrec[_ECD_ENTRIES_TOTAL] = dircount2
00202     endrec[_ECD_SIZE] = dirsize
00203     endrec[_ECD_OFFSET] = diroffset
00204     return endrec
00205 

Here is the caller graph for this function:

def zipfile.is_zipfile (   filename)
Quickly see if a file is a ZIP file by checking the magic number.

The filename argument may be a file or file-like object too.

Definition at line 151 of file zipfile.py.

00151 
00152 def is_zipfile(filename):
00153     """Quickly see if a file is a ZIP file by checking the magic number.
00154 
00155     The filename argument may be a file or file-like object too.
00156     """
00157     result = False
00158     try:
00159         if hasattr(filename, "read"):
00160             result = _check_zipfile(fp=filename)
00161         else:
00162             with open(filename, "rb") as fp:
00163                 result = _check_zipfile(fp)
00164     except IOError:
00165         pass
00166     return result

Here is the call graph for this function:

Here is the caller graph for this function:

def zipfile.main (   args = None)

Definition at line 1449 of file zipfile.py.

01449 
01450 def main(args = None):
01451     import textwrap
01452     USAGE=textwrap.dedent("""\
01453         Usage:
01454             zipfile.py -l zipfile.zip        # Show listing of a zipfile
01455             zipfile.py -t zipfile.zip        # Test if a zipfile is valid
01456             zipfile.py -e zipfile.zip target # Extract zipfile into target dir
01457             zipfile.py -c zipfile.zip src ... # Create zipfile from sources
01458         """)
01459     if args is None:
01460         args = sys.argv[1:]
01461 
01462     if not args or args[0] not in ('-l', '-c', '-e', '-t'):
01463         print(USAGE)
01464         sys.exit(1)
01465 
01466     if args[0] == '-l':
01467         if len(args) != 2:
01468             print(USAGE)
01469             sys.exit(1)
01470         zf = ZipFile(args[1], 'r')
01471         zf.printdir()
01472         zf.close()
01473 
01474     elif args[0] == '-t':
01475         if len(args) != 2:
01476             print(USAGE)
01477             sys.exit(1)
01478         zf = ZipFile(args[1], 'r')
01479         badfile = zf.testzip()
01480         if badfile:
01481             print("The following enclosed file is corrupted: {!r}".format(badfile))
01482         print("Done testing")
01483 
01484     elif args[0] == '-e':
01485         if len(args) != 3:
01486             print(USAGE)
01487             sys.exit(1)
01488 
01489         zf = ZipFile(args[1], 'r')
01490         out = args[2]
01491         for path in zf.namelist():
01492             if path.startswith('./'):
01493                 tgt = os.path.join(out, path[2:])
01494             else:
01495                 tgt = os.path.join(out, path)
01496 
01497             tgtdir = os.path.dirname(tgt)
01498             if not os.path.exists(tgtdir):
01499                 os.makedirs(tgtdir)
01500             with open(tgt, 'wb') as fp:
01501                 fp.write(zf.read(path))
01502         zf.close()
01503 
01504     elif args[0] == '-c':
01505         if len(args) < 3:
01506             print(USAGE)
01507             sys.exit(1)
01508 
01509         def addToZip(zf, path, zippath):
01510             if os.path.isfile(path):
01511                 zf.write(path, zippath, ZIP_DEFLATED)
01512             elif os.path.isdir(path):
01513                 for nm in os.listdir(path):
01514                     addToZip(zf,
01515                             os.path.join(path, nm), os.path.join(zippath, nm))
01516             # else: ignore
01517 
01518         zf = ZipFile(args[1], 'w', allowZip64=True)
01519         for src in args[2:]:
01520             addToZip(zf, src, os.path.basename(src))
01521 
01522         zf.close()

Here is the call graph for this function:


Variable Documentation

Initial value:
00001 ["BadZipFile", "BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED",
00002            "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile"]

Definition at line 25 of file zipfile.py.

Definition at line 134 of file zipfile.py.

Definition at line 133 of file zipfile.py.

Definition at line 140 of file zipfile.py.

Definition at line 136 of file zipfile.py.

Definition at line 137 of file zipfile.py.

Definition at line 135 of file zipfile.py.

Definition at line 138 of file zipfile.py.

Definition at line 139 of file zipfile.py.

Definition at line 141 of file zipfile.py.

Definition at line 132 of file zipfile.py.

Definition at line 96 of file zipfile.py.

Definition at line 88 of file zipfile.py.

Definition at line 92 of file zipfile.py.

Definition at line 91 of file zipfile.py.

Definition at line 84 of file zipfile.py.

Definition at line 83 of file zipfile.py.

Definition at line 90 of file zipfile.py.

Definition at line 97 of file zipfile.py.

Definition at line 99 of file zipfile.py.

Definition at line 95 of file zipfile.py.

Definition at line 86 of file zipfile.py.

Definition at line 85 of file zipfile.py.

Definition at line 94 of file zipfile.py.

Definition at line 87 of file zipfile.py.

Definition at line 98 of file zipfile.py.

Definition at line 100 of file zipfile.py.

Definition at line 82 of file zipfile.py.

Definition at line 89 of file zipfile.py.

Definition at line 93 of file zipfile.py.

Definition at line 72 of file zipfile.py.

Definition at line 69 of file zipfile.py.

Definition at line 63 of file zipfile.py.

Definition at line 64 of file zipfile.py.

Definition at line 65 of file zipfile.py.

Definition at line 66 of file zipfile.py.

Definition at line 73 of file zipfile.py.

Definition at line 68 of file zipfile.py.

Definition at line 62 of file zipfile.py.

Definition at line 67 of file zipfile.py.

Definition at line 116 of file zipfile.py.

Definition at line 112 of file zipfile.py.

Definition at line 115 of file zipfile.py.

Definition at line 119 of file zipfile.py.

Definition at line 110 of file zipfile.py.

Definition at line 109 of file zipfile.py.

Definition at line 118 of file zipfile.py.

Definition at line 111 of file zipfile.py.

Definition at line 114 of file zipfile.py.

Definition at line 113 of file zipfile.py.

Definition at line 108 of file zipfile.py.

Definition at line 117 of file zipfile.py.

Definition at line 20 of file zipfile.py.

zipfile.error = BadZipfileBadZipFile

Definition at line 38 of file zipfile.py.

Definition at line 79 of file zipfile.py.

Definition at line 60 of file zipfile.py.

Definition at line 130 of file zipfile.py.

Definition at line 124 of file zipfile.py.

Definition at line 106 of file zipfile.py.

Definition at line 78 of file zipfile.py.

Definition at line 59 of file zipfile.py.

Definition at line 129 of file zipfile.py.

Definition at line 123 of file zipfile.py.

Definition at line 105 of file zipfile.py.

string zipfile.structCentralDir = "<4s4B4HL2L5H2L"

Definition at line 77 of file zipfile.py.

Definition at line 58 of file zipfile.py.

Definition at line 128 of file zipfile.py.

Definition at line 122 of file zipfile.py.

string zipfile.structFileHeader = "<4s2B4HL2L2H"

Definition at line 104 of file zipfile.py.

tuple zipfile.ZIP64_LIMIT = (1 << 31)

Definition at line 41 of file zipfile.py.

Definition at line 47 of file zipfile.py.

Definition at line 42 of file zipfile.py.

tuple zipfile.ZIP_MAX_COMMENT = (1 << 16)

Definition at line 43 of file zipfile.py.

Definition at line 46 of file zipfile.py.

zipfile.zlib = None

Definition at line 22 of file zipfile.py.