[英]Get a specific file from s3 bucket (boto3)
所以我在存儲桶“ test”上有一個file.csv,正在創建一個新會話,我想下載該文件的內容:
session = boto3.Session(
aws_access_key_id=KEY,
aws_secret_access_key=SECRET_KEY
)
s3 = session.resource('s3')
obj = s3.Bucket('test').objects.filter(Prefix='file.csv')
這會返回一個集合,但是有沒有辦法直接獲取文件? 沒有任何循環,我想做類似的事情:
s3.Bucket('test').objects.get(key='file.csv')
我無需傳遞憑據即可達到相同的結果:
s3 = boto3.client('s3')
obj = s3.get_object(Bucket='test', Key='file.csv')
如果您查看client
方法:
import boto3
s3_client = boto3.client('s3')
s3_client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
和resource
方法:
import boto3
s3 = boto3.resource('s3')
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
您會注意到,您可以使用meta.client
從resource
轉換為client
。
因此,將其與您的代碼結合起來可獲得:
session = boto3.Session(aws_access_key_id=KEY, aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')
obj = s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
我喜歡mpu.aws.s3_download
,但我有偏見;-)
它是這樣的:
import os
import boto3
def s3_download(bucket_name, key, profile_name, exists_strategy='raise'):
session = boto3.Session(profile_name=profile_name)
s3 = session.resource('s3')
if os.path.isfile(destination):
if exists_strategy == 'raise':
raise RuntimeError('File \'{}\' already exists.'
.format(destination))
elif exists_strategy == 'abort':
return
s3.Bucket(bucket_name).download_file(key, destination)
對於身份驗證,建議使用環境變量。 有關詳細信息,請參見boto3:配置憑據 。
您可以使用以下boto3方法。
download_file(桶,密鑰,文件名,ExtraArgs =無,回調=無,配置=無)
s3 = boto3.resource('s3')
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
在此處找到更多詳細信息-download_file()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.