Here are three ways to unzip files in Python:
- Using extractall() Method
- Using extract() Method
- Using shutil.unpack_archive() Method
Method 1: Using extractall() Method
The most straightforward method is to use the extractall(), which extracts all the contents of the zip file.
If you don’t specify a path, the files will be extracted to the current working directory.
Example
from zipfile import ZipFile
with ZipFile('dir/data.zip', 'r') as zipObj:
# Extract all the contents of zip file in different directory
zipObj.extractall('temp')
print('File is unzipped in temp folder')
Output
File is unzipped in temp folder
Method 2: Using extract() Method
The extract() method in the zipfile module allows for the extraction of individual files from a zip archive, offering more control compared to the extractall() method.
Example
import zipfile
# Path to your zip file
zip_file_path = 'dir/data.zip'
# File name inside the zip to extract
file_to_extract = 'PHP array_chunk.jpg'
# Path where the file will be extracted
destination_folder = 'temp'
# Open the zip file in read mode
with zipfile.ZipFile(zip_file_path, 'r') as zipObj:
# Extract the specified file
zipObj.extract(file_to_extract, destination_folder)
print(f"File {file_to_extract} has been extracted to {destination_folder}")
Output
File PHP array_chunk.jpg has been extracted to temp
Method 3: Using shutil Module
For high-level operations such as extracting a zip file, the shutil module can be used.
The unpack_archive() function within this module handles the file unpacking process.
This method is particularly useful because it can handle different archive formats(like tar, gztar, bztar, xztar) automatically, based on the file extension.
Example
# importing shutil module
import shutil
# Path of the file
filename = "dir/data.zip"
# Target directory
extract_dir = "temp"
# Unzip the file
shutil.unpack_archive(filename, extract_dir)
Output
See Also
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
I don’t have .zip files, but ones ending with ,el; ,en; ,es; ,kl; ,no; ,ta; ,ko; and ,zh-CN; all downloaded after running PIP on a Coursera course. How do I decompress these ones?
The file extensions you’ve mentioned (.el, .en, .es, .kl, .no, .ta, .ko, and .zh-CN) don’t correspond to standard compression formats like .zip, .rar, or .tar.gz. Instead, these extensions seem to represent language codes (for example, .es for Spanish, .ko for Korean, .zh-CN for Simplified Chinese, etc.).
If these files are indeed not compressed archives, you won’t be able to “decompress” them in the traditional sense.