核心功能 - 批量压缩文件

实现代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import zipfile # zipfile库 压缩文件
import os
import time
 
 
def batch_zip(start_dir):
    start_dir = start_dir #文件路径
    file_news = start_dir + '.zip' # 压缩后文件夹的名字
 
    z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        #避免从根目录复制
        f_path = dir_path.replace(start_dir, '')
        #压缩所有文件
        f_path = f_path and f_path + os.sep
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), f_path + filename)
     z.close()
     return file_news
 
 
batch_zip('./data/ziptest')