Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 967 Bytes

108.md

File metadata and controls

36 lines (25 loc) · 967 Bytes
@author jackzhenguo
@desc 
@date 2019/10/8

108 批量压缩文件

import zipfile  # 导入zipfile,这个是用来做压缩和解压的Python模块;
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):
        # 这一句很重要,不replace的话,就从根目录开始复制
        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')
[上一个例子](107.md) [下一个例子](109.md)