zoukankan      html  css  js  c++  java
  • python zip 压缩文件

    import zipfile
    
    # 打开一个 ZIP 文件,file 为一个指向文件的路径(字符串)
    class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)
    # 返回一个列表,其中包含每个归档成员的 ZipInfo 对象。
    ZipFile.infolist()
    # 返回按名称排序的归档成员列表。
    ZipFile.namelist()
    # 从归档中提取出一个成员放入当前工作目录;member 必须为成员的完整名称或 ZipInfo 对象。 成员的文件信息会尽可能精确地被提取。 path 指定一个要提取到的不同目录。 member 可以是一个文件名或 ZipInfo 对象。 pwd 是用于解密文件的密码。
    ZipFile.extract(member, path=None, pwd=None)
    # 从归档中提取出所有成员放入当前工作目录。 path 指定一个要提取到的不同目录。 members 为可选项且必须为 namelist() 所返回列表的一个子集。 pwd 是用于解密文件的密码。
    ZipFile.extractall(path=None, members=None, pwd=None)
    # 归档成员的压缩类型。
    ZipInfo.compress_type
    # bytes 对象形式的单个归档成员的注释。
    ZipInfo.comment
    

    使用命令行

    创建一个新的 ZIP 归档,请在 -c 选项后指定其名称然后列出应当被包含的文件名

    python -m zipfile -c monty.zip spam.txt eggs.txt
    python -m zipfile -c monty.zip life-of-brian_1979/

    将一个 ZIP 归档提取到指定的目录,请使用 -e 选项

    python -m zipfile -e monty.zip target-dir/

    要获取一个 ZIP 归档中的文件列表

    python -m zipfile -l monty.zip

    实现一个类似于 -c 的程序

    import os
    import zipfile
    
    file_names = []
    for name, dirs, files in os.walk("little_spider"):
        for file_name in files:
            file_name = os.path.join(name, file_name)
            file_names.append(file_name)
    
    with zipfile.ZipFile("little.zip", "w") as zip:
        for file_name in file_names:
            zip.write(file_name)
            print(file_name, "is write end")
    
  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/iFanLiwei/p/13405267.html
Copyright © 2011-2022 走看看