Compress and Move Two Files to ZIP Format

  • Share this:

Code introduction


Compresses two files into a single ZIP file and moves the ZIP file to a specified directory.


Technology Stack : os, zipfile, shutil

Code Type : File operation

Code Difficulty : Intermediate


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

    # Create a zip file
    with zipfile.ZipFile('output.zip', 'w') as zipf:
        zipf.write(file1, os.path.basename(file1))
        zipf.write(file2, os.path.basename(file2))

    # Create a directory to hold the zip file
    if not os.path.exists('zipped_files'):
        os.makedirs('zipped_files')

    # Move the zip file to the new directory
    shutil.move('output.zip', 'zipped_files/')

    return 'output.zip' is not None                
              
Tags: