Compress and Save File to Zip

  • Share this:

Code introduction


This function takes a file path and a destination zip file path, compresses the specified file, and saves it to the target path.


Technology Stack : os, zipfile

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, destination_path):
    import os
    import zipfile

    def check_directory(directory):
        if not os.path.exists(directory):
            os.makedirs(directory)

    check_directory(os.path.dirname(destination_path))
    with zipfile.ZipFile(destination_path, 'w') as zipf:
        zipf.write(file_path)
    return destination_path                
              
Tags: