如何使用Boto3将S3中的gzip拼花文件读取到Python中?

时间:2019-04-17 16:56:20

标签: python amazon-web-services amazon-s3 boto3 parquet

我的S3存储桶中有一个名为data.parquet.gzip的文件。我无法弄清楚阅读该书有什么问题。通常,我使用StringIO,但不知道如何解决。我想使用pandas和boto3将其从S3导入到我的Python jupyter笔记本会话中。

1 个答案:

答案 0 :(得分:1)

解决方案实际上非常简单。

import boto3 # For read+push to S3 bucket
import pandas as pd # Reading parquets
from io import BytesIO # Converting bytes to bytes input file
import pyarrow # Fast reading of parquets

# Set up your S3 client
# Ideally your Access Key and Secret Access Key are stored in a file already
# So you don't have to specify these parameters explicitly.
s3 = boto3.client('s3',
                  aws_access_key_id=ACCESS_KEY_HERE,
                  aws_secret_access_key=SECRET_ACCESS_KEY_HERE)

# Get the path to the file
s3_response_object = s3.get_object(Bucket=BUCKET_NAME_HERE, Key=KEY_TO_GZIPPED_PARQUET_HERE)

# Read your file, i.e. convert it from a stream to bytes using .read()
df = s3_response_object['Body'].read()

# Read your file using BytesIO
df = pd.read_parquet(BytesIO(df))