You can download this code by clicking the button below.
This code is now available for download.
The function combines two files (in ZIP, TAR, or GZIP format) into one ZIP file.
Technology Stack : The function combines two files (in ZIP, TAR, or GZIP format) into one ZIP file.
Code Type : Function
Code Difficulty :
def zipfiles(file1, file2):
import os
import shutil
import zipfile
import tarfile
import gzip
import io
import contextlib
def create_zip(source, destination):
with zipfile.ZipFile(destination, 'w') as zipf:
zipf.write(source, os.path.basename(source))
def create_tar(source, destination):
with tarfile.open(destination, 'w') as tar:
tar.add(source, arcname=os.path.basename(source))
def create_gzip(source, destination):
with gzip.open(destination, 'wb') as gz:
with open(source, 'rb') as f_in:
shutil.copyfileobj(f_in, gz)
with contextlib.closing(io.BytesIO()) as buffer:
with buffer as f_out:
if file1.endswith('.zip'):
create_zip(file1, f_out)
elif file1.endswith('.tar'):
create_tar(file1, f_out)
elif file1.endswith('.gz'):
create_gzip(file1, f_out)
else:
raise ValueError("Unsupported file format for file1")
if file2.endswith('.zip'):
create_zip(file2, f_out)
elif file2.endswith('.tar'):
create_tar(file2, f_out)
elif file2.endswith('.gz'):
create_gzip(file2, f_out)
else:
raise ValueError("Unsupported file format for file2")
with open('combined.zip', 'wb') as out_file:
out_file.write(buffer.getvalue())
return 'combined.zip'