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.
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 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
.
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.
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.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.
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.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.