본문 바로가기
AWS

[AWS] Python으로 S3 Object(디렉터리 혹은 파일)의 용량 확인

by 초이MS 2021. 7. 8.

목적

  • AWS를 이용 시 S3내의 Object(S3에는 디렉터리의 개념이 없음)의 용량을 확인해야하는 경우가 있음
  • python boto3를 이용해 S3에 존재하는 Object의 용량을 확인해보자

과정

  • 다음의 코드를 작성하여 사이즈를 가져올 수 있었다. get_directory_size_bytes를 이용하며 해당 메서드의 결과값은 byte 단위이므로 이용 시 유의하여야한다.
    from boto3 import client
    
    def remove_prefix(text, prefix):
      if text.startswith(prefix):
      	return text[len(prefix):]
      return text
    
    def get_directory_size_bytes(s3Url):
      s3_client = client('s3')
      bucket_name = remove_prefix(s3Url, "s3://").split('/',1)[0]
      prefix = remove_prefix(s3Url, "s3://").split('/',1)[1]
    
      dir_info = s3_client.list_objects(Bucket=bucket_name, Prefix=prefix)['Contents']
    
      total_size = 0
    
      for object_in_dir in dir_info:
      	total_size = total_size + object_in_dir['Size']
    
      return total_size
  •  이용 방법은 다음과 같다.
    >>> get_directory_size_bytes("s3://my-bucket/depth1-obj/depth2-obj")
    123456789​
  • NoCredintialError 등이 발생한다면 aws configure를 이용해서 api키 등을 입력해야할 것이다.
반응형

댓글