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")
    
  • 相关阅读:
    Mysql主外键
    行列转换
    简单的增删改查
    day22 面向对象基础
    day21 xml模块 ATM+购物车
    python学习 day19 configparser模块 os模块 subprocess模块
    day18 logging模块 sys shelve
    day17 正则表达式 re模块和hashlib模块
    day16 包的使用 json time 常用模块
    day15模块内容
  • 原文地址:https://www.cnblogs.com/iFanLiwei/p/13405267.html
Copyright © 2011-2022 走看看