如何使用Python批量将多个txt文件压缩为gzip格式的.gz文件
Python批量gzip压缩txt文件实现方案
- 直接用
glob模块匹配所有.txt后缀文件,循环执行单文件压缩逻辑即可,使用with上下文管理器可自动处理文件开关,无需手动调用close()方法。
普通场景代码(适用于多数中小体积文件)
import gzip import glob import os # 匹配当前目录下所有txt文件,需指定目录则修改路径为 "目标目录/*.txt" 即可 txt_file_list = glob.glob("*.txt") for txt_file in txt_file_list: gz_file_name = txt_file + ".gz" with open(txt_file, "rb") as source_file, gzip.open(gz_file_name, "wb") as gz_file: gz_file.writelines(source_file) # 若压缩后无需保留原始txt文件,取消注释下行代码即可 # os.remove(txt_file)
大文件适配场景代码(避免内存占用过高)
如果待压缩的txt文件体积超过1GB,推荐使用逐块读取的方式压缩:
import gzip import glob import os # 单次读取块大小设置为10MB,可按需调整 READ_BLOCK_SIZE = 10 * 1024 * 1024 txt_file_list = glob.glob("*.txt") for txt_file in txt_file_list: gz_file_name = txt_file + ".gz" with open(txt_file, "rb") as source_file, gzip.open(gz_file_name, "wb") as gz_file: while True: file_block = source_file.read(READ_BLOCK_SIZE) if not file_block: break gz_file.write(file_block) # 同样可添加删除原文件的逻辑 # os.remove(txt_file)
内容的提问来源于stack exchange,提问作者Pavan Chowdary
相关产品推荐
相关产品推荐

