Categories
Python Answers

How to unzip files with Python?

Spread the love

Sometimes, we want to unzip files with Python.

In this article, we’ll look at how to unzip files with Python.

How to unzip files with Python?

To unzip files with Python, we can use the zipfile module.

For instance, we write:

import zipfile

path_to_zip_file = 'test.zip'
directory_to_extract_to = './test'

with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

We read the zip file into a Python object with zipfile.ZipFile(path_to_zip_file, 'r').

Then we call extractall on the returned zip file object to do the extraction.

We specify the directory_to_extract_to to extract the zip file’s contents.

Now we should see the test folder having the content of the zip file after the code is run.

Conclusion

To unzip files with Python, we can use the zipfile module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *