Compress and Relocate File to Zip Format

  • Share this:

Code introduction


This function compresses a file into a zip file and moves the original file to the same directory as the compressed file.


Technology Stack : os, zipfile, shutil

Code Type : File operation

Code Difficulty : Intermediate


                
                    
def zipfiles(file1, file2):
    import os
    import zipfile
    import shutil

    with zipfile.ZipFile(file1, 'w') as zipf:
        zipf.write(file2, arcname=os.path.basename(file2))

    shutil.move(file1, os.path.join(os.path.dirname(file2), 'zipped_' + os.path.basename(file1)))                
              
Tags: