Template request | Bug report | Generate Data Product
Tags: #zip #extract #file #operations #snippet #naas
Author: Maxime Jublou
Description: This notebook allows users to extract files from a ZIP archive.
import zipfile
import os
from pprint import pprint
file_path
: zip archive file pathoutput_dir
: directory name in which files will be extracted
# Inputs
file_path = "files.zip"
# Outputs
output_dir = "zip_extraction"
In this example, file_path
is the path of the ZIP archive that you want to extract.
The with statement is used to ensure that the ZIP file is closed properly after it has been read.
The ZipFile class is used to open the file in read mode ('r').
The extractall method is called to extract all the files in the archive to the current working directory.
You can also specify a different directory to extract the files to by passing a path to the extractall method.
# Create output dir
os.mkdir(output_dir)
# Extract files
if os.path.exists(file_path):
# open the zip file for reading
with zipfile.ZipFile(file_path, 'r') as zip_ref:
# extract all files to the current working directory
zip_ref.extractall(output_dir)
else:
print(f"❌ ZIP path '{file_path}' does not exist. Please update it on your variables.")
print("Number of files extracted:", len(os.listdir(output_dir)))
pprint(os.listdir(output_dir))