在 Python 中,我想读取一个存储在 zip 文件中的巨大 CSV 文件,但一次只能读取一个固定大小的块

In Python, I would like to read a huge CSV file stored in a zip file, but only a fixed sized chunk at a time

我正在处理一个 468 MB 的 zip 文件,其中包含一个 CSV 文本文件。我不想提取 entire 文本文件,所以我一次读取一个二进制块的 zip 文件。块大小大约为 65536 字节。

我知道我可以用 Python 的 csvfile 库读取文件,但在这种情况下,我提供给它的块不一定落在线边界.

我该怎么做? (p.s., 我不想使用 Pandas)

谢谢。

您只需要执行以下操作:

import zipfile
import io
import csv


with zipfile.ZipFile("test.zip") as zipf:
    with zipf.open("test.csv", "r") as f:
        reader = csv.reader(
            io.TextIOWrapper(f, newline='')
        )
        for row in reader:
            do_something(row)

假设您有一个像这样的 zip 存档:

jarrivillaga$ unzip -l test.zip
Archive:  test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
1308888890  04-01-2022 16:23   test.csv
---------                     -------
1308888890                     1 file

请注意,zipf.open returns 是二进制流,因此您可以使用 io.TextIOWrapper 使其成为文本流,它可以与任何 csv.readercsv.DictReader 个对象。

默认情况下,这应该以合理大小的块读取它,可能 io.DEFAULT_BUFFER_SIZE 是什么,因为查看 zipfile.ZipExtFile 源代码它是从 io.BufferedIOBase.[=19= 继承的]