2016-11-21 82 views
2

如何將CSV文件從本地上傳到我的S3存儲桶並讀取該scv文件。 請幫我一把。使用python在myBucket中上傳CSV並在S3中讀取文件使用python

bucket = aws_connection.get_bucket('mybucket') 
#with this i am able to create bucket 
folders = bucket.list("","/") 
    for folder in folders: 
    print folder.name 

現在想要將csv上傳到我的csv並讀取該文件。

回答

3

讓你在使用boto2我建議搬到boto3 - 請參見下面的幾個簡單的例子

boto2

上傳例如

import boto 
from boto.s3.key import Key 
bucket = aws_connection.get_bucket('mybucket') 
k = Key(bucket) 
k.key = 'myfile' 
k.set_contents_from_filename('/tmp/hello.txt') 

下載例子

import boto 
from boto.s3.key import Key 

bucket = aws_connection.get_bucket('mybucket') 
k = Key(bucket) 
k.key = 'myfile' 
k. get_contents_to_filename('/tmp/hello.txt') 

boto3

上傳例如

import boto3 
s3 = boto3.resource('s3') 
bucket = s3.Bucket('mybucket') 
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb')) 

或多個簡單

import boto3 
s3 = boto3.resource('s3') 
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt') 

下載例如

import boto3 
s3 = boto3.resource('s3') 
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt') 
print(open('/tmp/hello.txt').read()) 
+0

以及如何給予權限..如何使私人bucket.IF我的桶已經theres.How我可以使它私人? –

+0

最好的是直接從aws控制檯 –

+0

與桶策略一起工作很好的答案。是否有你喜歡的原因 '''s3 = boto3.resource('s3') s3.meta.client.download_file('mybucket','hello.txt','/tmp/hello.txt')''' ' 而不是 '''s3 = boto3.client('s3') s3.upload_file('/tmp/hello.txt','mybucket','hello.txt')''' ? – Peter