오뚝이개발자

AWS S3 객체 리스트 불러오기 2 본문

AWS

AWS S3 객체 리스트 불러오기 2

땅어 2020. 5. 12. 16:29
728x90
300x250

이전에 포스팅한 AWS S3 객체 리스트 불러오기 1 와 유사한 내용이다. 마찬가지로 아래의 코드도 S3의 버킷내의 객체를 읽어들이는 것이다. 차이점은 아래의 코드는 key값을 그대로 불러오는 파이썬 스크립트 코드라는 것이다. 이전 포스팅의 경우 버킷내 최상단의 객체들에 대해서만 읽어들이지만 아래 코드의 경우 말그대로 '모든' 객체에 대한 key값을 읽는 것이다.

import boto3

def get_all_s3_objects(s3, **base_kwargs):
    continuation_token = None
    while True:
        list_kwargs = dict(MaxKeys=1000, **base_kwargs)
        if continuation_token:
            list_kwargs['ContinuationToken'] = continuation_token
        response = s3.list_objects_v2(**list_kwargs)
        yield from response.get('Contents', [])
        if not response.get('IsTruncated'):  # At the end of the list?
            break
        continuation_token = response.get('NextContinuationToken')

with open("output.txt", "w") as f:
    for file in get_all_s3_objects(boto3.client('s3'), Bucket=<bucket-name>):
        print(file['Key'])
        f.write(file['Key']+'\n')

S3의 경우 한 번에 접근해 읽어들일 수 있는 객체 수에 1000개의 제한이 걸려있다. 따라서 반복문을 사용하여 끝까지 읽어주어야 한다. IsTruncated라는 key값이 바로 읽어들일 객체가 더 남아있는지 아닌지를 알려주는 flag이다.

728x90
300x250

'AWS' 카테고리의 다른 글

AWS S3 객체 리스트 불러오기 1  (0) 2020.05.12
Comments