Python zipfile

zipfile is a Python module that allows creating, reading, writing, appending, and listing ZIP files. In this Answer, we'll see how we can use the ZipFile class inside the zipfile module to work with the ZIP file format in Python.

Creating a ZIP archive

We can create a new Zip archive using the write() method available within the ZipFile class. Here's an example:

Welcome to Educative
Creating a new ZIP archive
  • Line 1: We import the zipfile module.

  • Line 3: We create a new ZIP archive named Text_Files.zip and set the mode parameter to w for writing.

  • Lines 4–5: We use the write() method to add files to the ZIP archive. The ZipFile class provides a number of other methods as well that we'll discuss later on.

If we run the above code, a new ZIP archive with the name Text_Files.zip will be created, which can be viewed in the terminal using the ls command. The ZIP archive will contain the files hello_world.txt and educative.txt.

Appending to a ZIP archive

If we want to append files to an existing ZIP archive, we can simply pass the name of that ZIP archive and set the mode parameter to a:

import zipfile
# The following will append the text files to Text_Files.zip archive
with zipfile.ZipFile('Text_Files.zip', 'a') as zipf:
zipf.write('hello_world.txt')
zipf.write('educative.txt')

In this case, the files hello_world.txt and educative.txt will be appended to the Text_Files.zip file if it already exists. If Text_Files.zip does not exist, it will be created.

Extracting a ZIP archive

To extract the contents of a ZIP archive, we can use the extractall() method also available within the ZipFile class. Here's an example:

Welcome to Educative
Extracting a ZIP archive

We have used the ls command to view files inside the contents directory.

  • Lines 3–5: We create a new ZIP archive named Text_Files.zip as stated earlier.

  • Lines 7–8: We open the Text_Files.zip archive in read mode, and extract its contents to a new directory named contents.

Run the above code to see the result.

Reading files inside a ZIP archive

To read a file inside the ZIP archive, we can use the read() method of the ZipFile class. The mode parameter needs to be set to r, as in the code below:

Welcome to Educative
Reading a file inside a ZIP archive
  • Lines 3–5: We create a new ZIP archive named Text_Files.zip as stated earlier.

  • Lines 7–9: We open Text_Files.zip in read mode. We then use the read method to read the contents of the file educative.txt inside the ZIP archive. Finally, we convert the binary string to a regular string using the decode() method, and print the result on the console.

Copyright ©2024 Educative, Inc. All rights reserved