How do I read a compressed file without unpacking it first?

Write and read a gzip-compressed CSV directly with pandas, total it in chunks, and stream it line by line with gzip.open.

After this lesson, you can read a gzip file of trades directly and total the shares per ticker even when the full table would not fit in memory.

How much smaller is the gzip file?

trades.to_csv("trades.csv.gz") writes a gzip-compressed CSV, because pandas chooses gzip for the .gz ending, and the million made-up trades take about a third of the bytes of the plain CSV. Ticker names and digits repeat throughout the file, so gzip can refer back to earlier sequences of bytes.

The trades are a million rows of AAA to EEE, with sizes in shares and prices in dollars per share, written to the folder gzip_demo. .stat().st_size gives a file’s size in bytes. A tiny file can grow, because gzip adds a header and a trailer.

Code: the made-up trades
import gzip
import shutil
from pathlib import Path

import numpy as np
import pandas as pd

demo = Path("gzip_demo")
shutil.rmtree(demo, ignore_errors=True)
demo.mkdir()
rng = np.random.default_rng(14)
price_level = {"AAA": 170.0, "BBB": 180.0, "CCC": 410.0, "DDD": 880.0, "EEE": 170.0}
n = 1_000_000
trades = pd.DataFrame({"ticker": rng.choice(list(price_level), n), "size": rng.integers(1, 1_000, n)})
trades["price"] = (trades["ticker"].map(price_level) * rng.normal(1, 0.01, n)).round(2)

The following box writes both files and compares their sizes.

trades.to_csv(demo / "trades.csv", index=False)
trades.to_csv(demo / "trades.csv.gz", index=False)
plain_bytes = (demo / "trades.csv").stat().st_size
gzip_bytes = (demo / "trades.csv.gz").stat().st_size
print(round(gzip_bytes / plain_bytes, 2), 3 * gzip_bytes < plain_bytes)
0.31 True

How do I read the gzip file with pandas?

pd.read_csv("trades.csv.gz") decompresses the file while it reads, and gives the same table as the plain file, so the first trade is 413 shares of AAA at 167.88 dollars. With chunksize=250_000, the same call reads the compressed file in chunks, and AAA’s shares total 99,946,604.

The table in memory is as large as from the plain file, so a table that does not fit needs chunks, as in the lesson on CSV chunks. The gzip file has fewer bytes to read and more work to decompress, so which read is faster depends on the machine.

The following box reads the file whole and in chunks.

packed = pd.read_csv(demo / "trades.csv.gz")
print(packed.equals(pd.read_csv(demo / "trades.csv")))
print(packed.head(1))
total_shares = pd.Series(dtype="Int64")
for chunk in pd.read_csv(demo / "trades.csv.gz", usecols=["ticker", "size"], dtype={"size": "Int64"}, chunksize=250_000):
    total_shares = total_shares.add(chunk.groupby("ticker")["size"].sum(), fill_value=0)
print(total_shares)
True
  ticker  size   price
0    AAA   413  167.88
ticker
AAA     99946604
BBB     99913562
CCC    100141038
DDD     99947211
EEE    100283996
dtype: Int64

How do I read the file one line at a time?

gzip.open(path, "rt") opens the compressed file as text that decompresses as it is read, so next(file) returns one line at a time and a loop can count the trades with only one line in memory. The header and the first trade come first, and the file holds 1,000,000 data lines.

.rstrip("\r\n") removes the line ending, and sum(1 for line in file) counts the remaining lines. A quoted CSV field can contain a line break, so files with such fields need csv.reader, which reads whole records.

The following box reads the header and the first trade and counts the lines.

with gzip.open(demo / "trades.csv.gz", "rt") as file:
    header = next(file).rstrip("\r\n")
    first_trade = next(file).rstrip("\r\n")
    data_lines = 1 + sum(1 for line in file)
print(header, first_trade, data_lines)
ticker,size,price AAA,413,167.88 1000000

Your turn

Read the compressed file record by record with csv.reader, total the shares per ticker, and compare the totals with the chunked pandas totals. You should see True.

defaultdict(int) starts each new ticker’s total at zero.

import csv
from collections import defaultdict

shares = defaultdict(int)
with gzip.open(demo / "trades.csv.gz", "rt", newline="") as file:
    reader = csv.reader(file)
    next(reader)
    for ticker, size, price in reader:
        shares[ticker] += int(size)
print(dict(sorted(shares.items())) == total_shares.astype("int64").to_dict())
True