ZipFile

The zipfile module handles files with the .zip extension, i.e. compressed folders.

Write the import zipfile statement at the beginning of every example.

Zipping files


z = zipfile.ZipFile("myZip.zip", "w")
z.write("file.txt")
z.write("file2.txt")
z.close()
                                    

namelist()


# Checking the contents of a zip file (a list of files)
z = zipfile.ZipFile("myZip.zip", "r")
print(z.namelist())
z.close()
                                    

Unzipping files

There are two ways of unzipping files.


z = zipfile.ZipFile("myZip.zip", "r")
for x in z.namelist():
    z.extract(x)
z.close()
                                    

z = zipfile.ZipFile("myZip.zip", "r")
z.extractall()
z.close()