python 打包下载

看百度网盘我们会发现这么一个需求,新建一个文件夹,然后向文件夹中上传文件,点击文件夹可以直接下载,下载的是一个压缩文件,将文件夹中所有文件全部打包了下载下来。

在python中,我们要做文件打包下载,需要用到模块 zipfile

python自带zipfile 模块用来读写压缩文件

zipfile常见模考和方法:

1、is_zipfile:判断是否路径是压缩文件

  zipfile.is_zipfile(filePath)

      

2、ZipFile

  zf = zipfile.ZipFile(path, mode, zipfile.compression, allowZip64)

    path:压缩文件路径

    mode:文件打开模式--> r:读;w:写;a:添加

    compression:zipfile用什么压缩方式

      ZIP_STORE:默认方式,只是存储模式,不压缩

      ZIP_DEFLATED:压缩

    allowZip64:当压缩文件大于2G时,需要设置为True。

3、ZipFile对象的方法:

  1)zf.infolist()

    返回一个list列表,内容是zip文件中子文件的ZipInfo对象。

    包含的字段有:文件名,压缩方式,文件权限模式(读写),文件大小等

    

  

  2)zf.getinfo(name)

    获取压缩文件中某个具体的文件的信息,name:压缩文件中的文件名

  3)zf.namelist()

    获取压缩文件在中所有文件名称列表

  4)zf.printdir()

    打印出压缩文件中所有文件信息

  

  5)zf.write(filename,actname)

    将文件添加到压缩文件中。

    filename:要添加到压缩文件中的文件路径

    actname:添加到压缩文件中的保存的文件名称

    如下:

      

    结果如下:

      

  6)zf.read(filename [, pwd])

    获取压缩文件内指定文件的二进制数据。

要压缩某路径path下的所有文件及文件夹,实现过程如下:

import zipfile

import os

def ZipFile(path, destPath):

  try:

    zf = zipfile.ZipFile(destPath, "w", zipfile.ZIP_DEFLATED)

    for dirpath,dirnames,filenames in os.walk(path):

      fpath = dirpath.replace(path, "")  # 将当前目录替换为空,即以当前目录为相对目录,如果当前目录下面还存在文件夹,则fpath为 【/子目录】

      fpath = fpath and fpath + os.sep or ""

      for file in filenames:

        z.write(os.path.join(dirpath, file), fpath+file)

    zf.close()

  except Exception as e:

    print(e)

解压:

 1、解压压缩文件中的某个特定文件:

  zf.extract(members,path)

 

 2、解压全部文件到指定路径

  zf.extractall(path)

猜你喜欢

转载自www.cnblogs.com/fiona-zhong/p/9931458.html
今日推荐