python:将CSV阅读器与从tarfile中提取的单个文件一起使用

问题描述 投票:0回答:2

[我正在尝试使用Python CSV reader读取使用.tar.gzPython's tarfile library文件中提取的CSV文件。

我有这个:

tarFile = tarfile.open(name=tarFileName, mode="r")
for file in tarFile.getmembers():
    tarredCSV = tarFile.extractfile(file)
    reader = csv.reader(tarredCSV)
    next(reader)    # skip header
    for row in reader:
        if row[3] not in CSVRows.values():
            CSVRows[row[3]] = row

tar文件中的所有文件都是CSV。

我在第一个文件上遇到异常。我在第一行next上收到此异常:

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

我如何打开所说的文件(不提取文件然后打开它?)>

[我正在尝试使用Python CSV阅读器来读取我使用Python的tarfile库从.tar.gz文件中提取的CSV文件。我有这个:tarFile = tarfile.open(name = tarFileName,mode =“ r”)for ...

python python-3.x csv tar
2个回答
0
投票

tarfile.extractfile返回一个io.BufferedReader对象,一个字节流,但是csv.reader需要一个文本流。您可以使用io.TextIOWrapper将字节流转换为文本流:


-1
投票

您需要向csv.reader提供类似文件的对象。

© www.soinside.com 2019 - 2024. All rights reserved.