You can download this code by clicking the button below.
This code is now available for download.
The function compresses the contents of a folder into zip, tar, gzip, or base64 format based on the input folder and output file type, or outputs the folder contents as a json format.
Technology Stack : os, zipfile, shutil, glob, tarfile, gzip, io, base64, json
Code Type : File processing
Code Difficulty : Intermediate
def zipfiles(file1, file2):
import os
import zipfile
import shutil
import glob
import tarfile
import gzip
import io
import base64
import json
def create_zip(input_folder, output_zip):
with zipfile.ZipFile(output_zip, 'w') as zipf:
for foldername, subfolders, filenames in os.walk(input_folder):
for filename in filenames:
filepath = os.path.join(foldername, filename)
zipf.write(filepath, os.path.relpath(filepath, input_folder))
def create_tar(input_folder, output_tar):
with tarfile.open(output_tar, "w") as tar:
for foldername, subfolders, filenames in os.walk(input_folder):
for filename in filenames:
filepath = os.path.join(foldername, filename)
tar.add(filepath, arcname=os.path.relpath(filepath, input_folder))
def create_gzip(input_folder, output_gzip):
with gzip.open(output_gzip, 'wb') as f:
for foldername, subfolders, filenames in os.walk(input_folder):
for filename in filenames:
filepath = os.path.join(foldername, filename)
with open(filepath, 'rb') as file_data:
f.writelines(file_data)
def create_base64(input_folder, output_base64):
with open(input_folder, 'rb') as file:
data = file.read()
base64_bytes = base64.b64encode(data)
with open(output_base64, 'wb') as file:
file.write(base64_bytes)
def create_json(input_folder, output_json):
with open(output_json, 'w') as json_file:
json.dump(glob.glob(input_folder + '/*'), json_file)
if os.path.isdir(file1):
if file2.endswith('.zip'):
create_zip(file1, file2)
elif file2.endswith('.tar'):
create_tar(file1, file2)
elif file2.endswith('.gz'):
create_gzip(file1, file2)
elif file2.endswith('.json'):
create_json(file1, file2)
elif file1.endswith('.zip'):
create_base64(file1, file2)
else:
raise ValueError("Unsupported file type or input/output configuration")