source

s3 버킷에서 bto3로 파일 내용 읽기

ittop 2023. 9. 9. 10:13
반응형

s3 버킷에서 bto3로 파일 내용 읽기

나는 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']

이제, 나는 파일의 실제 내용을 얻어야 합니다, a와 유사합니다.open(filename).readlines(). 가장 좋은 방법은 무엇입니까?

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()

리소스 대신 클라이언트 사용:

s3 = boto3.client('s3')
bucket='bucket_name'
result = s3.list_objects(Bucket = bucket, Prefix='/something/')
for o in result.get('Contents'):
    data = s3.get_object(Bucket=bucket, Key=o.get('Key'))
    contents = data['Body'].read()
    print(contents.decode("utf-8"))

당신은 고려해 볼 수 있습니다.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 = s3_source.read(1000)  # read 1000 bytes

찾기smart_openhttps://pypi.org/project/smart_open/ 에서

기본 구성과 다른 구성의 파일을 읽고 싶을 때는 직접 또는 복사 붙여넣기한 코드를 자유롭게 사용하십시오.

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()

만약 당신이 이미 알고 있다면,filename, 당신은 사용할 수 있습니다.boto3내장된

import boto3

from io import BytesIO

session = boto3.Session()
s3_client = session.client("s3")

f = BytesIO()
s3_client.download_fileobj("bucket_name", "filename", f)
print(f.getvalue())
import boto3

print("started")

s3 = boto3.resource('s3',region_name='region_name', aws_access_key_id='your_access_id', aws_secret_access_key='your access key')

obj = s3.Object('bucket_name','file_name')

data=obj.get()['Body'].read()

print(data)

s3 버킷에서 bto3를 사용하여 파일 내용에 접근하기 위한 정확하고 테스트된 코드입니다.게시일까지 제게 효과가 있습니다.

def get_file_contents(bucket, prefix):
    s3 = boto3.resource('s3')
    s3.meta.client.meta.events.register('choose-signer.s3.*', disable_signing)
    bucket = s3.Bucket(bucket)
    for obj in bucket.objects.filter(Prefix=prefix):
        key = obj.key
        body = obj.get()['Body'].read()
        print(body)
        return body

get_file_contents('coderbytechallengesandbox', '__cb__')

제게 최선의 방법은 다음과 같습니다.

result = s3.list_objects(Bucket = s3_bucket, Prefix=s3_key)
for file in result.get('Contents'):
    data = s3.get_object(Bucket=s3_bucket, Key=file.get('Key'))
    contents = data['Body'].read()
    #if Float types are not supported with dynamodb; use Decimal types instead
    j = json.loads(contents, parse_float=Decimal)
    for item in j:
       timestamp = item['timestamp']

       table.put_item(
           Item={
            'timestamp': timestamp
           }
      )

컨텐츠가 있으면 다른 루프를 통해 실행하여 다이나믹노드 테이블에 기록할 수 있습니다. 예를 들어...

이 경우 bto3의 대안은 s3fs입니다.

from s3fs import S3FileSystem
s3 = S3FileSystem()
bucket = 's3://your-bucket'

def read_file(key):
    with s3.open(f'{s3_path}/{key}', 'r') as file:  # s3://bucket/file.txt
        return file.readlines()

for obj in bucket.objects.all():
    key = obj.key
    lines = read_file(key)
    ...

Boto3는 이제 업데이트를 중단했습니다.Resources이제 권장되는 접근 방식은 다시 사용하는 것입니다.Client.

그래서 이제 @Climbs_lika_Spyder의 대답이 받아들여져야 한다고 생각합니다.

참조 : https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html

경고:AWS Python SDK 팀은 boto3의 리소스 인터페이스를 더 이상 지원하지 않을 계획입니다.리소스 모델과 관련된 새로운 변경 요청은 더 이상 고려되지 않으며 리소스 인터페이스는 다음 주요 버전의 AWS SDK for Python에서는 지원되지 않습니다.AWS SDK 팀은 SDK 간의 일관된 기능을 달성하기 위해 노력하고 있으며, 개별 SDK에 맞춤형 추상화를 구현하는 것은 지속 가능한 솔루션이 아닙니다.향후 기능 요청은 교차 SDK 수준에서 고려해야 합니다.

언급URL : https://stackoverflow.com/questions/36205481/read-file-content-from-s3-bucket-with-boto3

반응형