python:使用 CSV 阅读器从 tarfile 中提取单个文件

标签 python python-3.x csv tar

我正在尝试使用 Python CSV reader读取我使用 Python's tarfile library.tar.gz 文件中提取的 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?)

如何打开该文件(无需解压文件然后打开它)?

最佳答案

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

import io

...

reader = csv.reader(io.TextIOWrapper(tarredCSV, encoding='utf-8'))

关于python:使用 CSV 阅读器从 tarfile 中提取单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61069941/

相关文章:

python - 分钟。迭代绘制规则形状 ("turtle")

python - 计算名称的数值

python 记录 : Custom Python LogRecord Throwing an error

python - 使用 BeautifulSoup 中的 nextSibling 什么都不输出

python - 为什么用 python3 用正确的逻辑计算数字中的数字会出现错误的答案?

Java - 使用 Apache.commons.csv 编写 CSV 文件

python - docker : How to export/save classifying results outside a Docker (tensorflow) box?

python - 使用列中的列表整理 DataFrame 的最佳方法

python - 文件流 - ValueError : embedded null byte

r - 在 CSV 文件中附加一个向量作为一行