美文网首页
python zipfile打包压缩文件

python zipfile打包压缩文件

作者: 小黄不头秃 | 来源:发表于2022-11-03 02:10 被阅读0次

    可以使用zipfile模块进行文件压缩的操作。

    使用步骤:

    • 使用zipfile.ZipFile()创建一个压缩文件对象
      传入参数zipfile.ZipFile(保存路径+文件名,模式(w),zipfile.ZIP_DEFLATED)
    • 调用zip.write()将需要压缩的文件传入进去
      传入参数zip.write(打包文件路径)
    • 关闭文件 zip.close()

    简单使用:

    # 打包文件
    import zipfile 
    
    des_path = "./"
    
    zip = zipfile.ZipFile("../test.zip","w",zipfile.ZIP_DEFLATED)
    
    # 压缩批量文件
    for file in os.listdir(des_path):
        if file.endswith('.pdf'):
            zip.write(des_path+file) 
    zip.close()
    

    举个例子:将指定不同路径下的文件保存到临时文件夹中,并将所有文件压缩。

    # 打包文件
    import zipfile 
    import os 
    import time
    from time import sleep
    import shutil
    import random
    
    # 压缩文件
    filelist = ["../发票样例/20201223_通行费电子发票_2张/invoice/91510000709155317M_44308ed89a5c467e9ede236eb1efd8bc.pdf","../发票样例/20201223_通行费电子发票_3张/invoice/91510000689919120D_f3c17dea5202450daa1d6b293390644c.pdf"]
    # 先将不同目录下的文件复制到./temp下
    time = str(int(time.time())+random.randint(0,100000))# 防止冲突,因为有可能有人同时下载文件
    os.mkdir("./temp/"+time)
    des_path = "./temp/"+time+"/"
    zip = zipfile.ZipFile(des_path+"/test.zip","w",zipfile.ZIP_DEFLATED)
    # 将指定文件复制到临时文件夹下
    for i,file_path in enumerate(filelist):
        path = des_path + str(i) + ".pdf"
        f = open(path,"wb")
        src_file = open(file_path,"rb")
        f.write(src_file.read())
        f.close()
        src_file.close()
    # 压缩批量文件
    for file in os.listdir(des_path):
        if file.endswith('.pdf'):
            zip.write(des_path+file) 
    zip.close()
    sleep(3) # 等待发送
    shutil.rmtree(des_path) # 发送成功之后需要删除该文件夹
    

    相关文章

      网友评论

          本文标题:python zipfile打包压缩文件

          本文链接:https://www.haomeiwen.com/subject/dpzozrtx.html