Python之zipfile函数

1、zipfile.ZipFile(filename[,mode[,compression[,allowZip64]]])

zip_file = zipfile.ZipFile(file, "r")
mode:可选 r,w,a 代表不同的打开文件的方式;r 只读;w 重写;a 添加
compression:指出这个 zipfile 用什么压缩方法,默认是 ZIP_STORED,另一种选择是 ZIP_DEFLATED;
allowZip64:bool型变量,当设置为True时可以创建大于 2G 的 zip 文件,默认值 True

创建一个zip文件对象,Open the ZIP file with mode read “r”, write “w” or append “a”
a为追加压缩,不会清空原来的zip

2、zipfile.open(file)

打开压缩文档中的某个文件

3、zip_file.close()

关闭文件,必须有,释放内存

4、zip_file.namelist()

得到压缩包里所有文件

5、zip_file.extract(file, folder_abs)

循环解压文件到指定目录

6、读取zip文件

def zip_read_raw(file: Union[str, Path]) -> Tuple[Dict[str, Any], bytes]:
    file = Path(file)
    with zipfile.ZipFile(file, "r") as z_file:
        d_file = z_file.filelist[0]
        with z_file.open(d_file) as raw:
            data = raw.read()
            size_byte = data[12:20]
            size = int(size_byte.decode().strip(b'\x00'.decode()))
            header = data[20:size-1]
            header = header.decode('gbk')
            print(header)
 	return header

你可能感兴趣的:(Python,zipfile)