You can download this code by clicking the button below.
This code is now available for download.
This function compresses all files with the specified extension in the specified directory into a single zip file.
Technology Stack : os, zipfile
Code Type : File compression
Code Difficulty : Intermediate
def zip_file_directory(directory, file_extension):
import os
import zipfile
# 创建一个zip文件
zip_filename = f"{directory}.zip"
with zipfile.ZipFile(zip_filename, 'w') as zipf:
# 遍历指定目录
for foldername, subfolders, filenames in os.walk(directory):
for filename in filenames:
# 如果文件扩展名匹配,则添加到zip文件中
if filename.endswith(file_extension):
filepath = os.path.join(foldername, filename)
zipf.write(filepath, arcname=os.path.relpath(filepath, directory))
return zip_filename