从压缩文件夹内的文件夹中将txt文件作为pandas数据帧读取

问题描述

我想读取一个位于zip压缩文件夹内的文件夹中的txt文件作为熊猫数据框。

我研究了如何读取txt文件以及如何从压缩文件Load data from txt with pandasDownload Returned Zip file from URL中访问文件

问题是我的代码收到KeyError消息。

我认为是因为我的txt文件位于文件夹内的一个文件夹中?

感谢您的帮助!

# 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'