我正在尝试使用 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/