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
Line 1: We import the
zipfilemodule.Line 3: We create a new ZIP archive named
Text_Files.zipand set themodeparameter towfor writing.Lines 4–5: We use the
write()method to add files to the ZIP archive. TheZipFileclass 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 archivewith 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
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.zipas stated earlier.Lines 7–8: We open the
Text_Files.ziparchive in read mode, and extract its contents to a new directory namedcontents.
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
Lines 3–5: We create a new ZIP archive named
Text_Files.zipas stated earlier.Lines 7–9: We open
Text_Files.zipin read mode. We then use thereadmethod to read the contents of the fileeducative.txtinside the ZIP archive. Finally, we convert the binary string to a regular string using thedecode()method, and print the result on the console.
Free Resources