본문 바로가기
파이썬

파이썬 boto3를 사용하여 S3 버킷에서 파일 콘텐츠 읽기

by º기록 2020. 11. 7.
반응형

다음을 수행하여 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 () 와 유사하게 파일의 실제 내용을 가져와야합니다. 가장 좋은 방법은 무엇입니까?

 

해결 방법

 

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

 

참조 페이지 https://stackoverflow.com/questions/36205481

 

 

반응형

댓글