# 0x00 前言

在一次数据分析过程中,对方扔过来 40GB 的数据 – data.tar.gz .

我想着能不能直接用 pandas 直接读取这个文件呢?查找了一些资料,于是有了本文。

Python 中支持如下:

  • 数据压缩算法:zlib, gzip, bzip2 and lzma
  • 存档格式:zip 以及 tar

# 0x01 压缩是怎么回事?

# 0x02 zlib 与 gzip

gzip 依赖于 zlib

# 读取压缩文件
import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()

# 写入压缩文件
import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)

# 拷贝压缩文件
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

# 压缩二进制字符串
import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)

ChangeLog:

  • 2017-12-20 初始化本文