《Python内置模块010:gzip、zipfile用于处理压缩文件的模块》

gzip、zipfile:用于处理压缩文件的模块

一、常用方法

(一)gzip模块

(1)功能: 主要用于处理GNU zip格式的压缩文件(.gz)。它支持单一文件的压缩和解压缩。

(2)常用方法:

gzip.open(filename, mode): 打开一个gzip压缩文件,支持读('r')、写('w')、追加('a')等模式。

gzip.compress(data): 压缩数据并返回压缩后的字节对象。

gzip.decompress(data): 解压缩数据并返回解压后的字节对象。

(3)适用场景: 适合处理单个文件的压缩任务,常用于传输和存储日志文件。

(二)zipfile模块

(1)功能: 用于创建、读取、写入、追加、提取ZIP格式的压缩文件。ZIP文件可以包含多个文件和目录。

(2)常用方法:

zipfile.ZipFile(file, mode): 创建或打开一个ZIP文件,支持读('r')、写('w')、追加('a')等模式。

zipfile.ZipFile.write(filename, arcname): 将文件添加到ZIP文件中。

zipfile.ZipFile.extract(member, path): 从ZIP文件中提取指定的文件或目录。

zipfile.ZipFile.extractall(path): 提取ZIP文件中的所有内容到指定目录。

(3)适用场景: 适合处理多个文件和目录的压缩任务,常用于打包和分发软件、备份数据等。

二、使用案例

import gzip
import zipfile
import os

# 确保目录存在
os.makedirs('./tmp/', exist_ok=True)

# 创建示例文本文件
text_content = "这是一个用于压缩的示例文本文件内容。"
with open('./tmp/example.txt', 'w', encoding='utf-8') as file:
    file.write(text_content)

# 使用gzip压缩文件
with open('./tmp/example.txt', 'rb') as f_in:
    with gzip.open('./tmp/example.txt.gz', 'wb') as f_out:
        f_out.writelines(f_in)

# 使用gzip解压缩文件
with gzip.open('./tmp/example.txt.gz', 'rb') as f_in:
    with open('./tmp/example_unzipped.txt', 'wb') as f_out:
        f_out.writelines(f_in)

# 使用zipfile压缩文件
with zipfile.ZipFile('./tmp/example.zip', 'w') as zipf:
    zipf.write('./tmp/example.txt', arcname='example.txt')

# 使用zipfile解压缩文件
with zipfile.ZipFile('./tmp/example.zip', 'r') as zipf:
    zipf.extractall('./tmp/unzipped/')

# 输出解压后的文件内容
with open('./tmp/unzipped/example.txt', 'r', encoding='utf-8') as file:
    unzipped_content = file.read()

print("解压缩后的内容:", unzipped_content)

输出结果

解压缩后的内容: 这是一个用于压缩的示例文本文件内容。

你可能感兴趣的:(#,Python:各类模块(代码),python,数据库,服务器)