You can download this code by clicking the button below.
This code is now available for download.
This function compresses a file into a zip format and saves it to the specified output path.
Technology Stack : os, zipfile
Code Type : Function
Code Difficulty : Intermediate
def zip_file(file_path, output_path):
import os
import zipfile
def is_file_in_directory(directory, filename):
return any(filename in file for file in os.listdir(directory))
if not is_file_in_directory(os.path.dirname(file_path), os.path.basename(file_path)):
raise FileNotFoundError(f"The file {file_path} does not exist in the directory.")
with zipfile.ZipFile(output_path, 'w') as zipf:
zipf.write(file_path)
return f"File {file_path} has been added to {output_path}"