You can download this code by clicking the button below.
This code is now available for download.
This function takes a directory path and an output path, it will zip the directory into a zip file, rename it with a timestamp, and then move the zip file to the specified output path.
Technology Stack : os, zipfile, datetime, shutil
Code Type : File processing
Code Difficulty : Intermediate
def zip_file(file_path, output_path):
import os
import zipfile
from datetime import datetime
from shutil import copyfile
def create_zip(path, output):
with zipfile.ZipFile(output, 'w') as zipf:
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, path))
def timestamp():
return datetime.now().strftime("%Y%m%d%H%M%S")
if not os.path.exists(file_path):
raise FileNotFoundError(f"The directory {file_path} does not exist.")
if not os.path.isdir(file_path):
raise NotADirectoryError(f"The path {file_path} is not a directory.")
zip_filename = f"{output_path}_{timestamp()}.zip"
create_zip(file_path, zip_filename)
copyfile(zip_filename, output_path)
os.remove(zip_filename)
return zip_filename