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.
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.
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") asfile: header =next(file).rstrip("\r\n") first_trade =next(file).rstrip("\r\n") data_lines =1+sum(1for line infile)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.
TipShow answer
defaultdict(int) starts each new ticker’s total at zero.