如何在Python中以流式方式读取tar.zstd归档文件?
流式处理tar.zst文件(避免完全解压)
完全可以实现流式处理,无需把120GB的归档文件全解压到磁盘或内存。以下是两种Python实现方案:
方案一:使用zstandard库(推荐)
首先安装依赖:
pip install zstandard
通过zstandard创建流式解压对象,再传递给tarfile解析归档,全程流式处理:
import tarfile from zstandard import ZstdDecompressor with open("large_file.tar.zst", "rb") as zst_file: decompressor = ZstdDecompressor() with decompressor.stream_reader(zst_file) as decompressed_stream: # r|* 模式支持自动检测归档格式并流式读取 with tarfile.open(fileobj=decompressed_stream, mode="r|*") as tar: for entry in tar: # 按需过滤文件,这里仅处理文本文件 if entry.isfile() and entry.name.endswith(".txt"): with tar.extractfile(entry) as text_file: # 逐行处理文本,避免加载整个文件到内存 for line in text_file: # 替换为你的业务逻辑,比如分析、写入等 print(line.decode("utf-8").strip())
该方案纯Python实现,跨平台性强,内存占用可控,仅加载当前处理的文件片段。
方案二:借助系统zstd命令行工具
如果系统已安装zstd命令(Linux/macOS通常自带,Windows需单独安装),可通过subprocess创建管道实现流式处理:
import tarfile import subprocess # -dc 参数表示解压后输出到标准输出 with subprocess.Popen( ["zstd", "-dc", "large_file.tar.zst"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1024 * 1024 # 可根据内存情况调整缓冲区大小 ) as proc: with tarfile.open(fileobj=proc.stdout, mode="r|*") as tar: for entry in tar: if entry.isfile() and entry.name.endswith(".txt"): with tar.extractfile(entry) as text_file: for line in text_file: print(line.decode("utf-8").strip())
注意事项
- 两种方案均不会生成完整解压文件,全程流式读写,内存占用远低于120GB。
- 处理大文本文件时,逐行读取比一次性加载更高效。
- 若需处理非文本文件,只需调整过滤条件和读取逻辑即可。
内容的提问来源于stack exchange,提问作者Ron
相关产品推荐
相关产品推荐

