使用boto和pandas从aws s3读取csv文件

时间:2017-04-11 19:54:51

标签: python python-2.7 pandas amazon-s3 boto

我已经阅读了可用的答案herehere,但这些答案无效。

我正在尝试从csv存储桶读取S3对象,并且能够使用以下代码成功读取数据。

srcFileName="gossips.csv"
def on_session_started():
  print("Starting new session.")
  conn = S3Connection()
  my_bucket = conn.get_bucket("randomdatagossip", validate=False)
  print("Bucket Identified")
  print(my_bucket)
  key = Key(my_bucket,srcFileName)
  key.open()
  print(key.read())
  conn.close()

on_session_started()

但是,如果我尝试使用pandas作为数据框读取同一个对象,我会收到错误。最常见的是S3ResponseError: 403 Forbidden

def on_session_started2():
  print("Starting Second new session.")
  conn = S3Connection()
  my_bucket = conn.get_bucket("randomdatagossip", validate=False)
  #     url = "https://s3.amazonaws.com/randomdatagossip/gossips.csv"
  #     urllib2.urlopen(url)

  for line in smart_open.smart_open('s3://my_bucket/gossips.csv'):
     print line
  #     data = pd.read_csv(url)
  #     print(data)

on_session_started2()

我做错了什么?我在python 2.7上,不能使用Python 3。

3 个答案:

答案 0 :(得分:9)

以下是我在S3上成功阅读1[System.Int32]]]' to type 'System.Linq.IOrderedEnumerable的{​​{1}}所做的工作。

df

答案 1 :(得分:5)

这对我有用。

import pandas as pd
import boto3
import io

s3_file_key = 'data/test.csv'
bucket = 'data-bucket'

s3 = boto3.client('s3')
obj = s3.get_object(Bucket=bucket, Key=s3_file_key)

initial_df = pd.read_csv(io.BytesIO(obj['Body'].read()))

答案 2 :(得分:0)

也许您可以尝试使用熊猫read_sql和pyathena:

from pyathena import connect
import pandas as pd

conn = connect(s3_staging_dir='s3://bucket/folder',region_name='region')
df = pd.read_sql('select * from database.table', conn)
相关问题