You can download this code by clicking the button below.
This code is now available for download.
This function compresses all files and subfolders within a specified folder into a single zip file.
Technology Stack : os, zipfile
Code Type : File compression
Code Difficulty : Intermediate
def zip_file(input_folder, output_zip):
import os
import zipfile
# 创建zip文件
with zipfile.ZipFile(output_zip, 'w') as zipf:
# 遍历输入文件夹中的所有文件和文件夹
for foldername, subfolders, filenames in os.walk(input_folder):
for filename in filenames:
# 构建完整的文件路径
filepath = os.path.join(foldername, filename)
# 将文件添加到zip文件中
zipf.write(filepath, os.path.relpath(filepath, input_folder))
return output_zip