How to Use the zipfile module in Python

Source: Internet
Author: User
Tags zipinfo
This article mainly introduces how to use the zipfile module in Python. The zipfile module is used to operate zip files. If you need it, refer to the zip file format below, which is a common document compression standard, in the ziplib module, the ZipFile class is used to operate zip files. The following describes the operations:
Class zipfile. ZipFile (file [, mode [, compression [, allowZip64])

Create a ZipFile object to indicate a zip file. The file parameter indicates the file path or file-like object. The mode parameter indicates the mode in which the zip file is opened. The default value is 'R', indicating that the existing zip file is read, you can also create a zip file or overwrite an existing zip file for 'W' or 'A' and 'W, 'A' indicates attaching data to an existing zip file. The compression parameter indicates the compression method used for writing zip files. The value can be zipfile. ZIP_STORED or zipfile. ZIP_DEFLATED. If the size of the zip file to be operated exceeds 2 GB, set allowZip64 to True.

ZipFile also provides the following common methods and attributes:
ZipFile. getinfo (name ):

Obtains the information of a specified file in a zip file. Returns a zipfile. ZipInfo object, which includes detailed information about the file. This object is described in detail below.
ZipFile. infolist ()

Obtains information about all files in the zip file and returns a zipfile. ZipInfo list.
ZipFile. namelist ()

Obtains the name list of all files in the zip file.
ZipFile. extract (member [, path [, pwd])

Decompress the specified file in the zip file to the current directory. The member parameter specifies the name of the file to be decompressed or the corresponding ZipInfo object. The path parameter specifies the folder for saving the parsing file. The pwd parameter is the decompress password. Next, extract all the files in txt.zip under the program root directory to the D:/Work directory:

import zipfile, oszipFile = zipfile.ZipFile(os.path.join(os.getcwd(), 'txt.zip'))for file in zipFile.namelist():  zipFile.extract(file, r'd:/Work')zipFile.close()ZipFile.extractall([path[, members[, pwd]]])

Decompress all files in the zip file to the current directory. The default value of the parameter members is the list of all file names in the zip file. You can also set the name of the file to be decompressed.
ZipFile. printdir ()

Print the information in the zip file to the console.
ZipFile. setpassword (pwd)

Set the password for the zip file.
ZipFile. read (name [, pwd])

Obtains the binary data of a specified file in a zip file. The following example shows the usage of read(←. zip文 contains a TXT text file, read its binary data using the read () method, and save it to D:/txt.txt.

# Coding = gbkimport zipfile, oszipFile = zipfile. zipFile (OS. path. join (OS. getcwd (), 'txt.zip ') data = zipFile.read('txt.txt') (lambda f, d: (f. write (d), f. close () (open (r 'd:/txt.txt ', 'wb'), data) # a row of statements completes the file write operation. Think over it ~ _~ ZipFile. close () ZipFile. write (filename [, arcname [, compress_type])

Add the specified file to the zip file. Filename is the file path, and arcname is the name saved after being added to the zip file. The compress_type parameter indicates the compression method. Its value can be zipfile. ZIP_STORED or zipfile. ZIP_DEFLATED. The following example demonstrates how to create a zip file and add the file D:/test.doc to the compressed file.

import zipfile, oszipFile = zipfile.ZipFile(r'D:/test.zip'), 'w')zipFile.write(r'D:/test.doc', 'ok.doc', zipfile.ZIP_DEFLATED)zipFile.close()ZipFile.writestr(zinfo_or_arcname, bytes)

Writestr () supports writing binary data directly to compressed files.
Class ZipInfo

The ZipFile. getinfo (name) method returns a ZipInfo object, indicating the information of the corresponding file in the zip document. It supports the following attributes:

  • ZipInfo. filename: get the file name.
  • ZipInfo. date_time: Get the last modification time of the file. Returns a tuple containing six elements: (year, month, day, hour, minute, second)
  • ZipInfo. compress_type: compression type.
  • ZipInfo. comment: document description.
  • ZipInfo. extr: Extended item data.
  • ZipInfo. create_system: Obtain the system for creating the zip file.
  • ZipInfo. create_version: Get the PKZIP version of the created zip file.
  • ZipInfo. extract_version: Obtain the PKZIP version required to extract the zip file.
  • ZipInfo. reserved: reserved field. The current implementation always returns 0.
  • ZipInfo. flag_bits: zip flag.
  • ZipInfo. volume: The volume label of the file header.
  • ZipInfo. internal_attr: Internal attribute.
  • ZipInfo. external_attr: External attribute.
  • ZipInfo. header_offset: the offset of the file header.
  • ZipInfo. CRC: CRC-32 for unzipped files.
  • ZipInfo. compress_size: obtains the compressed size.
  • ZipInfo. file_size: obtains the size of uncompressed files.

The following simple example illustrates the meaning of these attributes:

import zipfile, oszipFile = zipfile.ZipFile(os.path.join(os.getcwd(), 'txt.zip'))zipInfo = zipFile.getinfo('doc.doc')print 'filename:', zipInfo.filenameprint 'date_time:', zipInfo.date_timeprint 'compress_type:', zipInfo.compress_typeprint 'comment:', zipInfo.commentprint 'extra:', zipInfo.extraprint 'create_system:', zipInfo.create_systemprint 'create_version:', zipInfo.create_versionprint 'extract_version:', zipInfo.extract_versionprint 'extract_version:', zipInfo.reservedprint 'flag_bits:', zipInfo.flag_bitsprint 'volume:', zipInfo.volumeprint 'internal_attr:', zipInfo.internal_attrprint 'external_attr:', zipInfo.external_attrprint 'header_offset:', zipInfo.header_offsetprint 'CRC:', zipInfo.CRCprint 'compress_size:', zipInfo.compress_sizeprint 'file_size:', zipInfo.file_sizezipFile.close()

It seems very easy to use the zipfile module to process zip files. I wanted to use sharpziplib to compress and decompress a file on the. NET platform. It took me more than N times to find more than N English resources to write a demo that can compress the file. Now I use Python. by reading the python manual, I learned how to use the zipfile module in an hour or two. Haha, it's amazing to use Python!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.