Compress and Append Files to Zip

  • Share this:

Code introduction


Compresses two files into a single zip file. If the zip file already exists, it adds the two files to the zip file.


Technology Stack : os, zipfile

Code Type : File operation

Code Difficulty : Intermediate


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

    def create_zip(file_list, output_zip):
        with zipfile.ZipFile(output_zip, 'w') as zipf:
            for file in file_list:
                zipf.write(file, os.path.basename(file))

    if not os.path.exists(output_file):
        create_zip([file1, file2], output_file)
    else:
        with zipfile.ZipFile(output_file, 'a') as zipf:
            zipf.write(file1, os.path.basename(file1))
            zipf.write(file2, os.path.basename(file2))

    return output_file                
              
Tags: