Zipping a File into a Zip Archive

  • Share this:

Code introduction


This function zips a file into a zip file.


Technology Stack : os, zipfile

Code Type : File operation

Code Difficulty : Intermediate


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

    # Check if the file exists
    if not os.path.exists(file_path):
        raise FileNotFoundError("The file does not exist.")
    
    # Create a zipfile object
    with zipfile.ZipFile(destination, 'w') as zipf:
        # Add the file to the zipfile
        zipf.write(file_path, os.path.basename(file_path))
    
    return destination                
              
Tags: