Compress File into Zip and Return Path

  • Share this:

Code introduction


This function compresses a file at the specified path into a zip file and returns the path of the generated zip file.


Technology Stack : os, zipfile, json

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, output_path):
    import os
    import zipfile
    import json

    def is_file_in_directory(directory, filename):
        return any(filename in os.listdir(directory) for directory, _, filenames in os.walk(directory) for filename in filenames)

    if not is_file_in_directory(os.getcwd(), file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist in the current directory.")

    with zipfile.ZipFile(output_path, 'w') as zipf:
        zipf.write(file_path, os.path.basename(file_path))

    return output_path                
              
Tags: