Directory to Zip Conversion Tool

  • Share this:

Code introduction


This function accepts two parameters: the path to the directory to be compressed and the output path of the zip file. The function uses the zipfile module to compress the specified directory into a zip file.


Technology Stack : zipfile, os

Code Type : File compression

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time
import json
import html
import base64
import random
import string
import threading
import zipfile
import pickle
import queue

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def zip_directory(directory_path, zip_path):
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for foldername, subfolders, filenames in os.walk(directory_path):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                zipf.write(file_path, os.path.relpath(file_path, directory_path))

def xxx(arg1, arg2):
    try:
        if not isinstance(arg1, str) or not isinstance(arg2, str):
            raise ValueError("Both arguments must be strings.")
        
        if not os.path.isdir(arg1):
            raise ValueError(f"The provided directory path {arg1} does not exist.")
        
        zip_file_path = arg2
        zip_directory(arg1, zip_file_path)
        
        return f"Directory {arg1} has been successfully zipped to {zip_file_path}."
    except Exception as e:
        return str(e)                
              
Tags: