python 压缩文件为zip格式

1.创建zip压缩对像
f=zipfile.ZipFile(file, mode="", compression=ZIP_STORED, allowZip64=False)
“file”:生成的文件路径+名称
mode='w’压缩文件
2.将文件写入zip压缩文件
f.write(filepath)将文件直接写入压缩文件
f.write(filepath,dstdir+filename)将文件打包成一个文件夹进行压缩
3.关闭zip对象
f.close()

import os
import zipfile
import argparse

def zip_file(src_dir,video_name):

    zip_face_name=zipfile.ZipFile(src_dir+'/'+video_name+'_face.zip','w',zipfile.ZIP_DEFLATED)
    zip_human_name=zipfile.ZipFile(src_dir+'/'+video_name+'_human.zip','w',zipfile.ZIP_DEFLATED)

    for dirpath, dirnames, filenames in os.walk(src_dir):
        face_dir='/'+video_name+'_face/'
        human_dir='/'+video_name+'_human/'
        for filename in filenames:
            if 'F' in filename:
                zip_face_name.write(os.path.join(src_dir,filename),os.path.join(face_dir,filename))
            if 'H' in filename:
                zip_human_name.write(os.path.join(src_dir,filename),os.path.join(human_dir,filename))

    zip_face_name.close()
    zip_human_name.close()

if __name__=='__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--imgdir', type=str)
    args = parser.parse_args()
    src_dir=args.imgdir

    src_dir='/Users/hutingting/Desktop/low'

    list=src_dir.split('/')
    video_name=list[len(list)-1]
    zip_file(src_dir,video_name)



你可能感兴趣的:(python学习笔记)