You can download this code by clicking the button below.
This code is now available for download.
The function takes two file paths and an output path, compresses the two files into a ZIP file, then extracts them to a temporary directory, and verifies that the files are correctly included. After that, it cleans up the temporary directory.
Technology Stack : os, zipfile, shutil
Code Type : Function
Code Difficulty :
def zipfiles(file1, file2, output):
import os
import zipfile
import shutil
# Create a zipfile object
with zipfile.ZipFile(output, 'w') as z:
# Add file1 to the zipfile
z.write(file1, os.path.basename(file1))
# Add file2 to the zipfile
z.write(file2, os.path.basename(file2))
# Copy the files to a temporary directory
temp_dir = 'temp_zip'
os.makedirs(temp_dir, exist_ok=True)
with zipfile.ZipFile(output, 'r') as z:
z.extractall(temp_dir)
# Verify that both files are in the temporary directory
files_in_zip = os.listdir(temp_dir)
assert os.path.basename(file1) in files_in_zip and os.path.basename(file2) in files_in_zip, "Files not found in the zip file."
# Clean up
shutil.rmtree(temp_dir)
return True