You can download this code by clicking the button below.
This code is now available for download.
This function zips all files and folders within a specified directory into a zip file.
Technology Stack : os, zipfile, json
Code Type : File operation
Code Difficulty : Intermediate
def zip_file_directory(file_path, output_path):
import os
import zipfile
import json
def zip_directory(path, zipf):
for root, dirs, files in os.walk(path):
for file in files:
zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), path))
if not os.path.exists(file_path):
raise FileNotFoundError(f"The directory {file_path} does not exist.")
if not os.path.isdir(file_path):
raise NotADirectoryError(f"The path {file_path} is not a directory.")
with zipfile.ZipFile(output_path, 'w') as zipf:
zip_directory(file_path, zipf)
return output_path