Compress Directory to Zip File and Remove Original

  • Share this:

Code introduction


This function compresses all files in the specified directory into a zip format and saves the result to the specified output path. It first defines an internal function zipdir, which recursively adds all files in the directory to the zip file. Then it creates a zip file using the zipfile module and calls the zipdir function to add files. Finally, it uses shutil.rmtree to delete the original directory.


Technology Stack : os, zipfile, shutil

Code Type : Function

Code Difficulty : Intermediate


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

    def zipdir(path, ziph):
        for root, dirs, files in os.walk(path):
            for file in files:
                ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), start=path))

    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        zipdir(file_path, zipf)
    shutil.rmtree(file_path)                
              
Tags: