Прочитайте содержимое файла из ведра S3 с помощью boto3
Я читаю имена файлов в своем ведре S3, делая
objs = boto3.client.list_objects(Bucket='my_bucket')
while 'Contents' in objs.keys():
objs_contents = objs['Contents']
for i in range(len(objs_contents)):
filename = objs_contents[i]['Key']
Теперь мне нужно получить фактическое содержимое файла, аналогично open(filename).readlines()
. Каков наилучший способ?
Ответы
Ответ 1
boto3 предлагает модель ресурса, которая упрощает задачи, подобные итерации через объекты. К сожалению, StreamingBody не предоставляет readline
или readlines
.
s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
key = obj.key
body = obj.get()['Body'].read()
Ответ 2
Вы также можете рассмотреть модуль smart_open
, который поддерживает итераторы:
from smart_open import smart_open
# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
print(line.decode('utf8'))
и контекстные менеджеры:
with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
for line in s3_source:
print(line.decode('utf8'))
s3_source.seek(0) # seek to the beginning
b1000 = fin.read(1000) # read 1000 bytes
Найдите smart_open
адресу https://pypi.org/project/smart_open/
Ответ 3
Если вы хотите прочитать файл с конфигурацией, отличной от конфигурации по умолчанию, не стесняйтесь использовать либо mpu.aws.s3_read(s3path)
напрямую, либо скопированный код:
def s3_read(source, profile_name=None):
"""
Read a file from an S3 source.
Parameters
----------
source : str
Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
profile_name : str, optional
AWS profile
Returns
-------
content : bytes
botocore.exceptions.NoCredentialsError
Botocore is not able to find your credentials. Either specify
profile_name or add the environment variables AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
See https://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
session = boto3.Session(profile_name=profile_name)
s3 = session.client('s3')
bucket_name, key = mpu.aws._s3_path_split(source)
s3_object = s3.get_object(Bucket=bucket_name, Key=key)
body = s3_object['Body']
return body.read()