You can download this code by clicking the button below.
This code is now available for download.
This function compresses all files in the specified directory into a zip file and returns the timestamp when the compression is completed.
Technology Stack : os, zipfile, json, datetime
Code Type : File operation
Code Difficulty : Intermediate
def zip_file(file_path, output_path):
import os
import zipfile
import json
import datetime
def list_files(directory):
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
def get_timestamp():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def create_zip(directory, output):
with zipfile.ZipFile(output, 'w') as zipf:
for file in list_files(directory):
zipf.write(os.path.join(directory, file), arcname=file)
return get_timestamp()
try:
zip_time = create_zip(file_path, output_path)
return f"Zip file created at {zip_time}"
except Exception as e:
return f"An error occurred: {e}"