Zipfile - Extract

Here’s a concise explanation of extracting a in Python, along with security considerations. Basic Zipfile Extraction (Python) import zipfile Extract all contents with zipfile.ZipFile('your_file.zip', 'r') as zip_ref: zip_ref.extractall('destination_folder') # extracts to specified folder Extract a Single File with zipfile.ZipFile('your_file.zip', 'r') as zip_ref: zip_ref.extract('specific_file.txt', 'destination_folder') List Contents Before Extracting with zipfile.ZipFile('your_file.zip', 'r') as zip_ref: for file_info in zip_ref.infolist(): print(f"{file_info.filename} - {file_info.file_size} bytes") ⚠️ Security Warning: Zip Slip Vulnerability When extracting zip files, malicious archives can contain paths like ../../etc/passwd to write outside the destination folder. Safe Extraction Code: import zipfile import os def safe_extract(zip_path, extract_path): with zipfile.ZipFile(zip_path, 'r') as zip_ref: for member in zip_ref.namelist(): # Resolve the absolute path member_path = os.path.join(extract_path, member) abs_path = os.path.abspath(member_path)

# Check if the file is inside the extract directory if not abs_path.startswith(os.path.abspath(extract_path)): raise Exception(f"Zip slip attempt blocked: {member}") zip_ref.extractall(extract_path) safe_extract('your_file.zip', 'safe_folder/') Alternative: Using shutil (Python 3.11+) import shutil shutil.unpack_archive('your_file.zip', 'destination_folder') Command Line (Terminal) # Linux/macOS unzip your_file.zip -d destination_folder Windows PowerShell Expand-Archive -Path your_file.zip -DestinationPath destination_folder zipfile extract