How to unzip a file with python

Compressed files are very useful because they allow us to have a large number of files in one and that they take up less space than what is normally occupied by storing each one.

It is important to know how to deal with these types of files help to automate processes if we find them, there are two ways to compress a file with python, one comes by default with it and the other is an external library.

Zipfile

Comes by default with python.

import zipfile # create a objecto to manipulate de zip

zip_file = zipfile.ZipFile("file.zip")# to see a list of all files inside the zip

zip_file.namelist() # to extract a specific file

zip_file.extract("file.txt")# to extract all files inside

zip_file.extractall()

# To save a file into a zip
zip_file.write("document.txt", compress_type = zipfile.ZIP_DEFLATED)# At least you need you need to close the file

zip_file.close()

Patoolib

You need to installed, it works with zip, tar and gz files.

# pip3 install patoolimport patoolib# to unzip the entire file
patoolib.extract_archive("file.gz",
                           outdir="unzip") # dir to unzip files

image.png