You can download this code by clicking the button below.
This code is now available for download.
This function compresses all files and folders in a specified directory into a single zip file and returns the path to the zip file and the creation time.
Technology Stack : os, zipfile, datetime
Code Type : File compression
Code Difficulty : Intermediate
def zip_file(directory, file_name):
import os
import zipfile
from datetime import datetime
# 创建一个zip文件
zip_file_path = os.path.join(directory, file_name + ".zip")
with zipfile.ZipFile(zip_file_path, 'w') as zipf:
# 遍历指定目录下的所有文件和文件夹
for foldername, subfolders, filenames in os.walk(directory):
for filename in filenames:
# 将文件添加到zip文件中
file_path = os.path.join(foldername, filename)
zipf.write(file_path, os.path.relpath(file_path, directory))
# 获取zip文件的创建时间
creation_time = datetime.fromtimestamp(os.path.getctime(zip_file_path)).strftime('%Y-%m-%d %H:%M:%S')
return zip_file_path, creation_time