【Python】zipfile实现压缩及解压

边处理边压缩

import zipfile
from scipy import misc
import os
import numpy as np
import glob

def yasuo_file():
    files = glob.glob(r'E:\need_zip\*')
    f = zipfile.ZipFile(r'E:\zip_save\\' + str("ss") +".zip", 'w', zipfile.ZIP_DEFLATED)

    for file in files:
        f.write(file, os.path.split(file)[-1])
    f.close()

def single_yasuo_file():
    z = zipfile.ZipFile(r'E:\zip_save\ss.zip', 'w', zipfile.ZIP_DEFLATED) #打包,zipfile.ZIP_STORED是默认参数
    # z = zipfile.ZipFile('ss.zip', 'w', zipfile.ZIP_DEFLATED) #压缩
    for i in range(10000):
        save_path = os.path.join(r"E:\need_zip", str(i)+".jpg")
        img = np.random.randint(256,size=(96,96,3), dtype=np.uint8)
        misc.imsave(save_path, img)
        z.write(save_path, str(i)+".jpg")
    z.close()

def jieya_file():
    f = zipfile.ZipFile(r'E:\zip_save\ss.zip', 'r')
    for file in f.namelist():  # f.namelist()返回列表,列表中的元素为压缩文件中的每个文件
        f.extract(file, "ss/")
    f.close()

if __name__ == "__main__":
    # yasuo_file()
    jieya_file()
    # single_yasuo_file()

 

你可能感兴趣的:(Python)