问题描述
我想读取一个位于zip压缩文件夹内的文件夹中的txt文件作为熊猫数据框。
我研究了如何读取txt文件以及如何从压缩文件夹Load data from txt with pandas和Download Returned Zip file from URL中访问文件。
问题是我的代码收到KeyError
消息。
感谢您的帮助!
# MWE
import requests
import pandas as pd
from zipfile import ZipFile
from io import BytesIO
txt_raw = 'hcc-data.txt'
zip_raw = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00423/hcc-survival.zip'
r = requests.get(zip_raw)
files = ZipFile(BytesIO(r.content))
df_raw = pd.read_csv(files.open(txt_raw),sep=",",header=None)
# ERROR
KeyError: "There is no item named 'hcc-data.txt' in the archive"
解决方法
您需要为文件添加完整路径:
txt_raw = 'hcc-survival/hcc-data.txt'