You can download this code by clicking the button below.
This code is now available for download.
This function creates a zip file containing all files from a specified directory and allows setting the creation time of the zip file.
Technology Stack : os, json, shutil, zipfile, datetime, stat, sys
Code Type : Function
Code Difficulty :
def zip_file_directory(directory, filename):
import os
import json
import shutil
import zipfile
import datetime
import stat
import sys
def get_files(directory):
return [os.path.join(dp, f) for dp, dn, filenames in os.walk(directory) for f in filenames]
def create_zip_file(files, filename):
with zipfile.ZipFile(filename, 'w') as zipf:
for file in files:
zipf.write(file, os.path.basename(file))
def set_zip_file_time(zip_file, time_str):
zipf = zipfile.ZipFile(zip_file, 'a')
for file in zipf.namelist():
zipf.setmod(file, stat.S_IREAD)
zipf.utime(file, (datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S').timestamp(), datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S').timestamp()))
zipf.close()
files_to_zip = get_files(directory)
create_zip_file(files_to_zip, filename)
set_zip_file_time(filename, '2023-04-01 12:00:00')
return f"Zip file '{filename}' created with files from '{directory}'."