You can download this code by clicking the button below.
This code is now available for download.
This function compresses the specified file into a zip format and saves it to the specified path.
Technology Stack : os, zipfile
Code Type : File compression
Code Difficulty : Intermediate
def zip_file(file_path, output_path):
import os
import zipfile
def is_file_in_directory(directory, file_name):
return os.path.exists(os.path.join(directory, file_name))
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, os.path.basename(file_path))
return output_path