Extract files

Tags: #zip #extract #file #operations #snippet #naas
Author: Maxime Jublou
Description: This notebook allows users to extract files from a ZIP archive.


Import libraries

import zipfile
import os
from pprint import pprint

Setup Variables

  • file_path: zip archive file path
  • output_dir: directory name in which files will be extracted
# Inputs
file_path = ""
# Outputs
output_dir = "zip_extraction"


Extract files

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
# 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
print(f"❌ ZIP path '{file_path}' does not exist. Please update it on your variables.")


Display result

print("Number of files extracted:", len(os.listdir(output_dir)))
Last modified 1mo ago