Compress and Package Two Files into a Tar Zip File

  • Share this:

Code introduction


This function compresses two files into a zip file, then packages this zip file into a tar file, deletes the intermediate zip file, and finally returns the name of the packaged file.


Technology Stack : os, shutil, zipfile, tempfile, json, tarfile, datetime, time, math, random, re, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    import os
    import shutil
    import zipfile
    import tempfile
    import json
    import tarfile
    import datetime
    import time
    import math
    import random
    import re
    import string

    def generate_random_string(length=10):
        return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

    with tempfile.NamedTemporaryFile(delete=False, suffix='.zip') as temp_zip:
        with zipfile.ZipFile(temp_zip.name, 'w') as zipf:
            zipf.write(file1)
            zipf.write(file2)
        zip_name = f'zip_{generate_random_string()}.zip'

    shutil.move(temp_zip.name, zip_name)

    with tarfile.open(zip_name, 'w') as tar:
        tar.add(zip_name, arcname=zip_name)

    os.remove(zip_name)

    return zip_name