编程语言
首页 > 编程语言> > Python zipfile 压缩不包含绝对路径

Python zipfile 压缩不包含绝对路径

作者:互联网

import os
import zipfile

def zip_path(filepaths):
    '''
    压缩文件
    :param filepaths:  压缩文件源目录
    :return:
    '''
    for file in filepaths:
        zip = zipfile.ZipFile("{}.zip".format(file), 'w', zipfile.ZIP_DEFLATED)
        if os.path.isdir(file):
            for dirpath, dirnames, filenames in os.walk(file):
                for filename in filenames:
                    # 压缩时不带绝对路径,但是携带目录
                    zip.write(os.path.join(dirpath, filename), arcname=os.path.join(dirpath, filename).split(file)[1])

                    # zip.write(os.path.join(dirpath, filename))
        else:
            zip.write(file)
        zip.close()
    return True

标签:zip,Python,zipfile,绝对路径,file,dirpath,path,filename,os
来源: https://www.cnblogs.com/knva/p/16646260.html