1. 程式人生 > >解壓縮模組zipfile — Work with ZIP archives(檔案檔案)

解壓縮模組zipfile — Work with ZIP archives(檔案檔案)

zipfile是一個module ,有兩個非常重要的class, 分別是ZipFile和ZipInfo, 在絕大多數的情況下,我們只需要使用這兩個class就可以了。ZipFile是主要的類,用來建立和讀取zip檔案,ZipInfo是儲存的zip檔案的每個檔案的資訊的。

簡介:ZIP檔案格式是一種常見的歸檔( archive)和壓縮(compression)標準。該模組提供了建立、讀取、寫入、追加和列出zip檔案的工具。任何先進的使用此模組將需要了解格式,如定義在PKZIP應用筆記。該模組目前不處理多盤ZIP檔案。它可以處理使用ZIP64擴充套件的ZIP檔案(即大小大於4 GIB的zip檔案)。它支援在zip檔案中解密加密檔案,但目前無法建立加密檔案。解密是非常緩慢的,因為它是在本地Python中實現的,而不是C。

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None)     

引數:(1)Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object. (2)The mode parameter should be 'r' to read an existing file, 'w' to truncate(截斷) and write a new file, 'a'

to append(拓展) to an existing file, or 'x' to exclusively(專門的特定的) create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised.If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe
). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable.(3)compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED.(4)If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions.(5)The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).

支援with語句: ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs:

from zipfile import ZipFile
with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

類ZipFile的方法如下

ZipFile.close()      Close the archive file. You must call close() before exiting your program or essential records will not be written.

ZipFile.namelist()     Return a list of archive members by name.

ZipFile.infolist()      Return a list containing a ZipInfo object for each member of the archive. The objects are in the same order as their entries in the actual ZIP file on disk if an existing archive was opened.

ZipFile.extract(member, path=None, pwd=None)     Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files.Returns the normalized path created (a directory or new file).

ZipFile.extractall(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 op

ZipFile.printdir()          Print a table of contents for the archive to sys.stdout.

ZipFile.setpassword(pwd)         Set pwd as default password to extract encrypted files.

ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)       name can be either the name of a file within the archive or a ZipInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. pwd is the password used to decrypt encrypted ZIP files.  open() is also a context manager and therefore supports the with statement:

from zipfile import ZipFile
with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:   使用with statement
        print(myfile.read())

With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError.When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files.

ZipFile.read(name, pwd=None)       Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available.

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)      Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. Similarly, compresslevel will override the constructor if given. The archive must be open with mode 'w', 'x' or 'a'.