Compress and Move Files into a Single Zip Archive

  • Share this:

Code introduction


This function compresses two files into a single zip file and moves it to the directory of the first file.


Technology Stack : os, zipfile, shutil

Code Type : File processing

Code Difficulty : Intermediate


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

    def get_file_path(directory, filename):
        return os.path.join(directory, filename)

    # Create a zip file at the specified path
    zip_path = get_file_path(file1, 'archive.zip')
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        # Add file1 to the zip file
        zipf.write(file1, os.path.basename(file1))
        # Add file2 to the zip file
        zipf.write(file2, os.path.basename(file2))

    # Verify if the zip file is created
    if os.path.exists(zip_path):
        shutil.move(zip_path, get_file_path(os.path.dirname(file1), 'archive.zip'))
        return True
    else:
        return False                
              
Tags: