Загрузка...

Python One-Liner: Zip a Directory into a ZIP File! 📦✨ #PythonTips #CodingShorts

Compressing an entire folder into a single ZIP file is essential for backups, deployments, and file sharing in Python

Long Way (zipfile + os.walk):

Import Modules: Use the built-in os and zipfile libraries for maximum control

Walk the Directory: os.walk(src_dir) yields every subdirectory and file path.

Add to ZIP: For each file, compute its relative path within the archive and call zipf.write(full, rel) to preserve structure

Close Archive: Finalize the ZIP file with zipf.close(), producing archive.zip.

One-Liner (shutil.make_archive):

shutil.make_archive(base_name, format, root_dir) creates an archive in one call

Example:

import shutil
shutil.make_archive('archive', 'zip', root_dir='my_folder')

Automatically zips my_folder into archive.zip in the current directory.

Why Use the One-Liner?

Concise & Readable: Eliminates boilerplate loops and manual writes.

Cross-Format: Supports 'zip', 'tar', 'gztar', 'bztar', and 'xztar'

Thread-Safe (3.10+): Updated to avoid self-archiving when used with default formats

Use these patterns in your Jupyter notebooks to quickly archive project folders, take snapshots for versioning, or create downloadable bundles—ideal for CodeVisium Shorts!

Codes:

Long Way: Recursively add files using zipfile:

import os, zipfile
src_dir = 'my_folder'
# Directory to compress
zipf = zipfile.ZipFile('archive.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(src_dir):
for file in files:
full = os.path.join(root, file)
rel = os.path.relpath(full, src_dir)
zipf.write(full, rel)
# Preserve folder structure
zipf.close()
# Output: archive.zip created

One-Liner: Use shutil.make_archive()

import shutil
print(shutil.make_archive('archive', 'zip', root_dir='my_folder'))
# Output: 'archive.zip' (created in current directory)

Видео Python One-Liner: Zip a Directory into a ZIP File! 📦✨ #PythonTips #CodingShorts канала CodeVisium
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять