Compress Directory to Zip File

  • Share this:

Code introduction


This function compresses all files in the specified directory into a zip format and saves it to the specified output path.


Technology Stack : os, zipfile

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(input_path, output_path):
    import os
    import zipfile

    with zipfile.ZipFile(output_path, 'w') as zipf:
        for root, dirs, files in os.walk(input_path):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, input_path))
    return output_path                
              
Tags: