我在S3上保存了一个制表符分隔的文本文件,需要将其加载到pandas中,但由于我正在Heroku服务器上运行,无法先保存该文件。以下是我目前的进展。
import io
import boto3
import os
import pandas as pd
os.environ["AWS_ACCESS_KEY_ID"] = "xxxxxxxx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xxxxxxxx"
s3_client = boto3.client('s3')
response = s3_client.get_object(Bucket="my_bucket",Key="filename.txt")
file = response["Body"]
pd.read_csv(file, header=14, delimiter="\t", low_memory=False)
错误信息是:
OSError: Expected file path name or file-like object, got <class 'bytes'> type
如何将响应体转换为 pandas 可接受的格式?
pd.read_csv(io.StringIO(file), header=14, delimiter="\t", low_memory=False)
returns
TypeError: initial_value must be str or None, not StreamingBody
pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)
returns
TypeError: 'StreamingBody' does not support the buffer interface
更新 - 使用以下内容有效
file = response["Body"].read()
and
pd.read_csv(io.BytesIO(file), header=14, delimiter="\t", low_memory=False)
io.BytesIO(file)
或io.StringIO(file)
代替read_csv()
调用中的file
。 - MaxU - stand with Ukraineio.StringIO
。 - IanS