Python ZipFile module details

  • 2020-04-02 13:03:36
  • OfStack

The Python zipfile module is used for zip coding and decompression. There are two very important classes in zipfile, namely zipfile and ZipInfo. In most cases, we only need to use these two classes. ZipFile is the main class that creates and reads zip files and ZipInfo is the information for each file of the stored zip file.
For example, to read a Python zipfile module, assume that filename is the path to a file:

import zipfile  
z =zipfile.ZipFile(filename, 'r') 
#  The second parameter here is r The representation is read zip File, w Is to create a zip file   
for f in z.namelist(): 
print f

The code above reads the names of all the files in a zip. Z.namelist () returns a list of all file names in the zip package.
Here's another one:

import zipfile  
z = zipfile.ZipFile(filename, 'r')  
for i in z.infolist():  
print i.file_size, i.header_offset 

Here, z.i. nfolist() is used, and it returns information about all the files in the zip package, a ZipInfo list. A ZipInfo object contains the information of a file in the compression package, among which filename, file_size, and header_offset are commonly used. They are respectively the filename, file size, and offset of the file data in the compression package. In fact, the previous z.namelist() is the filename in the ZipInfo that is read, which constitutes the list returned.
To extract a file from a ZipFile, use the ZipFile read method:

import zipfile  
 z = zipfile.ZipFile(filename, 'r')  
print z.read(z.namelist()[0]) 

This will fetch the first file in z.namelist() and output it to the screen or, of course, save it to a file. Here's how to create a zip package, similar to how to read it:

import zipfile, os  
 z = zipfile.ZipFile(filename, 'w') 
#  Notice that the second parameter here is w Here, filename It's the name of the package 

Suppose you want to add a file called testdir to your zip (here, only the files in a subdirectory) :

if os.path.isdir(testdir):  
     for d in os.listdir(testdir):  
         z.write(testdir+os.sep+d)  
         # close()  Must be called!   
         z.close() 

The code is very simple. One more question to think about, what if I add a test/111.txt to my zip and then I want to put it in my zip to test22/111.txt? This is actually the second parameter in the write method of the Python ZipFile module. Just call:

z.write("test/111.txt", "test22/111.txt")  

That's all we've learned about the Python ZipFile module.

Related articles: