Common methods of ZipFile module in Python3

Source: Internet
Author: User
Tags zipinfo

A brief introduction of ZipFile module

ZipFile is used in Python to do zip format encoding compression and decompression, because it is a very common zip format, so this module use frequency is also relatively high,

Here are some notes on how to use ZipFile. That is convenient for themselves and others.

There are two very common classes in ZipFile, namely ZipFile and Zipinfo, and in most cases we only need to use these two classes.

ZipFile is the primary class that is used to create and read Zip files while zipinfo is storing information for each file in a zip file.

Here's a brief introduction to the basic operations of these two classes:

Second, ZipFile and zipinfo These two classes of basic operations 1, class ZipFile. ZipFile (file[, mode[, compression[, AllowZip64]])

Creates a ZipFile object that represents a zip file. The parameter file represents the path or class file object (File-like object) of the files, and the parameter mode indicates how to open the zip file

The default value is ' R ', which means to read the existing zip file, or ' W ' or ' A ', ' W ' to create a new zip document or overwrite an existing zip document.

Import'r'#  Here's the second parameter with R means to read the zip file, W or a is to create a zip file for   in#z.namelist () returns a list of all file names within the compressed package.     Print(f_name)# The above code reads the names of all the files in a ZIP archive package. 
three modes of the parameter mode instance

' A ' means attaching data to an existing ZIP document. The parameter compression represents the compression method used when writing the zip document, and its value can be zipfile. zip_stored or zipfile. zip_deflated. If the zip file you want to manipulate is larger than 2G, you should set ALLOWZIP64 to true.

ZipFile also provides the following common methods and properties:

Zipfile.getinfo (name)

Gets the information for the specified file within the zip document. Returns a ZipFile. A Zipinfo object that includes details about the file.

Zipfile.infolist ()

Gets information about all the files in the Zip document and returns a ZipFile. A list of zipinfo.

Zipfile.namelist ()

Gets a list of the names of all the files in the zip document.

Zipfile.extract (member[, path[, PWD])

Extracts the specified files in the zip document to the current directory. The parameter member specifies the name of the file to decompress or the corresponding Zipinfo object, and the parameter path specifies the folder where the file is parsed;

The parameter pwd is the decompression password. The following example extracts all the files in the duoduo.zip that are stored in the program root directory to the D:/work directory:

Import ZipFile, OSF = ZipFile. ZipFile (Os.path.join (OS.GETCWD (), ' Duoduo.zip '))  #拼接成一个路径for file in F.namelist (): f.extract (file, R ' D:/work ')     #在d: Extracting files from/work f.close ()

Above is the usage of OS.GETCWD!!

Zipfile.extractall ([path[, members[, PWD]])

Unzip all the files in the zip document into the current directory. The default value for the members of the parameter is a list of all the file names in the zip document, or you can set them yourself, and select the name of the file to unzip.

Zipfile.printdir ()

Print the information in the ZIP document to the console.

Zipfile.setpassword (PWD)

Sets the password for the zip document.

Zipfile.read (name[, PWD])

Gets the binary data for the specified file within the zip document. The following example shows the use of Read (), which includes a duoduo.txt text file in the zip document, reads the binary data using the Read () method, and then saves it to D:/duoduo.txt.

ImportZipFile, Oszipfile= ZipFile. ZipFile (Os.path.join (OS.GETCWD (),'Duoduo.zip')) Data= Zipfile.read ('Duoduo.txt')#( Lambda F, D: (F.write (d), F.close ())) (Open (R ' d:/duoduo.txt ', ' WB '), data) #一行语句就完成了写文件操作. Think about it, ~_~ .With open (r'D:/duoduo.txt','WB') as F: forDinchData:f.write (d) zipfile.close ()

Zipfile.write (filename[, arcname[, Compress_type])

Adds the specified file to the zip document. FileName is the file path, Arcname is the name saved after adding to the zip document, the parameter Compress_type represents the compression method, and its value can be zipfile. zip_stored or zipfile. zip_deflated. The following example shows how to create a zip document and add the file D:/test.doc to the compressed document.

Import ZipFile, Oszipfile = ZipFile. ZipFile (R ' D:/test.zip '), ' W ') Zipfile.write (R ' D:/test.doc ', ' Saved name ', ZipFile. zip_deflated) Zipfile.close ()

Zipfile.writestr (zinfo_or_arcname, bytes)

WRITESTR () supports writing binary data directly to a compressed document.

2. Class Zipinfo

zipfile.getinfo (name) The Zipinfo method returns an object that represents the information for the corresponding file in the zip document. It supports the following properties:

Zipinfo.filename:Gets the file name.
Zipinfo.date_time:Gets the last modified time of the file. Returns a tuple containing 6 elements: (year, month, day, time, minute, second)
Zipinfo.compress_type:The compression type.
zipinfo.comment:Document description.
zipinfo.extr:The extension data.
Zipinfo.create_system:Gets the system that created the zip document.
zipinfo.create_version:Gets the pkzip version of the zip document that was created.
zipinfo.extract_version:Gets the PKZIP version required to unzip the zip document.
zipinfo.reserved:Reserved field, the current implementation always returns 0.
zipinfo.flag_bits:The ZIP flag bit.
Zipinfo.volume:The volume label of the file header.
zipinfo.internal_attr:Internal properties.
zipinfo.external_attr:External properties.
Zipinfo.header_offset:File header offset.
ZIPINFO.CRC:The CRC-32 of the uncompressed file.
zipinfo.compress_size:Gets the size after compression.
zipinfo.file_size:Gets the uncompressed file size.

The following simple example illustrates the meaning of these attributes:

ImportZipFile, Oszipfile= ZipFile. ZipFile (Os.path.join (OS.GETCWD (),'Duoduo.zip')) Zipinfo= Zipfile.getinfo ('Files in file. txt')Print('FileName:', Zipinfo.filename)#Get file namePrint('date_time:', Zipinfo.date_time)#gets the last modified time of the file. Returns a tuple containing 6 elements: (year, month, day, time, minute, second)Print('Compress_type:', Zipinfo.compress_type)#Compression TypePrint('Comment:', zipinfo.comment)#Document DescriptionPrint('Extra:', Zipinfo.extra)#Extended Item DataPrint('Create_system:', Zipinfo.create_system)#gets the system that created the zip document. Print('create_version:', zipinfo.create_version)#gets the pkzip version of the zip document that was created. Print('extract_version:', zipinfo.extract_version)#gets the PKZIP version required to unzip the zip document. Print('extract_version:', zipinfo.reserved)#reserved field, the current implementation always returns 0. Print('flag_bits:', zipinfo.flag_bits)#The zip flag bit. Print('Volume:', Zipinfo.volume)#the volume label of the file header. Print('internal_attr:', zipinfo.internal_attr)#internal properties. Print('external_attr:', zipinfo.external_attr)#External properties. Print('Header_offset:', Zipinfo.header_offset)#file header offset. Print('CRC:', ZIPINFO.CRC)#the CRC-32 of the uncompressed file. Print('compress_size:', zipinfo.compress_size)#gets the size after compression. Print('file_size:', zipinfo.file_size)#gets the uncompressed file size. Zipfile.close ()#

Common methods of ZipFile module in Python3

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.