Python to Unzip File with Source Code

In this article, you’ll learn how to Unzip File using python

Prerequisites:

  1. Python Basics
  2. zipfile module

What is Zip file?

  • ZIP is an archive file format that supports lossless data compression.
  • A ZIP file may contain one or more files or directories that may have been compressed.
  • ZIP files can come handy for a lot different things, we make use of it on a regular basis.

Uses for Zip File:

  • Zip files help you to put all related files in one place.
  • Zip files help to reduce the data size.
  • Zip files transfer faster than the individual file over many connections.

Install Necessary Modules:

  • Since zipfile is in-built module, hence no need to install it separately.
  • ZipFile module provides tools to create, read, write, append, and list a ZIP file.
  • Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.
  • Now that you are familiar with Zip file use cases and have acquired basic knowledge of ZipFile module, we can move forward to the coding section.

Source Code:

'''
Python Program to Unzip File
'''

# Import the necessary module!
import zipfile as zip

# Set the target file
target = "demo.zip"

# Display a start message
print("Starting to Unzip the File")

# Use ZipFile method
root = zip.ZipFile(target)

# Give destination path
# If the folder with name `unzip` already exists, it will create an unzipped file inside it. 
# Otherwise, a new folder will be created with the given name (even if no parameter is passed).
root.extractall("unzip")
# End the process using close method.
root.close()

# Display the end message
print("\nFile is Succesfully Unzipped!")

Output:

Starting to Unzip the File File is Succesfully Unzipped!

Leave a Comment