ZIP File Creation from Directory

  • Share this:

Code introduction


This function zips all files and subdirectories in a specified directory into a single ZIP file.


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file(input_path, output_path):
    import os
    import zipfile
    with zipfile.ZipFile(output_path, 'w') as zipf:
        for foldername, subfolders, filenames in os.walk(input_path):
            for filename in filenames:
                filepath = os.path.join(foldername, filename)
                zipf.write(filepath, os.path.relpath(filepath, input_path))
    return output_path                
              
Tags: