How do I read a file inside a ZIP archive?

List the files inside a ZIP archive, read the one you need with pandas, and do it from the bytes of a download held in memory.

After this lesson, you can read the table from a ZIP archive that also holds a README, straight from the bytes of a download.

How do I see which files a ZIP holds?

zipfile.ZipFile(...).namelist() lists the files inside the archive, called members, and this archive holds factors_monthly.csv and README.txt. .infolist() gives one record per member with its size in bytes before and after compression.

The archive holds six months of made-up factor returns in percent, such as the market return above the risk-free rate, mkt_rf, and a README, and its bytes in data stand for a download. io.BytesIO(data) wraps the bytes as a file in memory, so zipfile.ZipFile opens them like a file on disk, and a ZIP on disk opens with its name, zipfile.ZipFile("factors.zip"). with closes the archive at the end of the block.

Code: the made-up ZIP
import io
import zipfile

import pandas as pd

buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
    archive.writestr("factors_monthly.csv", "month,mkt_rf,smb,hml,rf\n202401,1.12,-0.62,0.83,0.40\n202402,3.85,1.47,-1.56,0.41\n202403,-0.94,-2.08,2.19,0.40\n202404,2.41,0.35,-0.47,0.42\n202405,-1.73,0.91,1.02,0.41\n202406,0.58,-1.24,0.66,0.40\n")
    archive.writestr("README.txt", "Monthly factor returns in percent. Made-up values for a teaching example.\n")
data = buffer.getvalue()

The following box lists the members and their sizes.

with zipfile.ZipFile(io.BytesIO(data)) as archive:
    print(archive.namelist())
    print([(info.filename, info.file_size, info.compress_size) for info in archive.infolist()])
['factors_monthly.csv', 'README.txt']
[('factors_monthly.csv', 193, 118), ('README.txt', 74, 69)]

How do I read the CSV inside it?

archive.open("factors_monthly.csv") opens one member for reading, and pd.read_csv reads it like a file, so the six months arrive as a table with February’s market return of 3.85%. pd.read_csv on the whole ZIP raises a ValueError here, because pandas reads a ZIP directly only when it holds a single file.

index_col="month" makes the month the row label. The table stays in factors after the archive closes.

The following box reads the CSV member and tries the whole ZIP.

with zipfile.ZipFile(io.BytesIO(data)) as archive, archive.open("factors_monthly.csv") as file:
    factors = pd.read_csv(file, index_col="month")
print(factors)
try:
    pd.read_csv(io.BytesIO(data), compression="zip")
except ValueError as error:
    print(type(error).__name__)
        mkt_rf   smb   hml    rf
month                           
202401    1.12 -0.62  0.83  0.40
202402    3.85  1.47 -1.56  0.41
202403   -0.94 -2.08  2.19  0.40
202404    2.41  0.35 -0.47  0.42
202405   -1.73  0.91  1.02  0.41
202406    0.58 -1.24  0.66  0.40
ValueError

Your turn

Print the text of README.txt. You should see that the returns are in percent.

archive.read returns the member’s bytes, and .decode("utf-8") turns them into text.

with zipfile.ZipFile(io.BytesIO(data)) as archive:
    print(archive.read("README.txt").decode("utf-8"))
Monthly factor returns in percent. Made-up values for a teaching example.