gpt4 book ai didi

python - 使用 python-3.x 从 zip 存档中读取 CSV 文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:00 25 4
gpt4 key购买 nike

我有一个包含多个 csv 文件的压缩存档。

例如,假设 myarchive.zip 包含 myfile1.csvmyfile2.csvmyfile3.csv

python 2.7 中,我能够使用 pandas 迭代加载所有 myfiles

import pandas as pd
import zipfile

with zipfile.ZipFile(myarchive.zip, 'r') as zippedyear:
for filename in ['myfile1.csv', 'myfile2.csv', 'myfile3.csv']:
mydf = pd.read_csv(zippedyear.open(filename))

现在用 Python 3 做同样的事情会抛出错误

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

我在这里不知所措。知道是什么问题吗?谢谢!

最佳答案

确实很奇怪,因为您可以指定的唯一模式是 r/w(字符模式)。

这里有一个解决方法;使用 file.read 读取文件,将数据加载到 StringIO 缓冲区,并将其传递给 read_csv

from io import StringIO

with zipfile.ZipFile(myarchive.zip, 'r') as zippedyear:
for filename in ['myfile1.csv', 'myfile2.csv', 'myfile3.csv']:
with zippedyear.open(filename) as f:
mydf = pd.read_csv(io.StringIO(f.read()))

关于python - 使用 python-3.x 从 zip 存档中读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50259792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com