본문 바로가기

AWS

[AWS] Boto3로 s3에 있는 파일 읽기

Boto3로 s3 버킷에 접근하고 객체 읽어오는 방법

 

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html

 

S3 - Boto3 1.34.159 documentation

Previous ListRumMetricsDestinations

boto3.amazonaws.com

 

s3 버킷 리스트 조회

import boto3
from pprint import pprint

s3 = boto3.client("s3")

res = s3.list_buckets()
pprint(res)

 

해당 코드 실행 시 아래와 같이 모든 bucket 정보가 나온다.

 

여기서 유의미한건 Name이랑 생성날짜 정도이니 아래와 같이 코드만 약간 수정하면 좀 더 보기 좋게 출력할 수 있다.

import boto3

s3 = boto3.client("s3")

res = s3.list_buckets()

for bucket in res["Buckets"]:
    name = bucket["Name"]
    date = bucket["CreationDate"]
    print(f"'{name}' bucket was created {date}")

 

 

 

s3 버킷 내 객체 조회

from pprint import pprint
import boto3

s3 = boto3.client("s3")
res = s3.list_objects(Bucket="bucket-name")

pprint(res)

 

해당 코드로 간단하게 버킷 내 존재하는 모든 객체들을 가져올 수 있다.

 

만약 특정 객체에 대한 정보를 가져오고자 하면 get_object 모듈을 사용하여 불러올 수 있다. get_object는 버킷명과 객체명이 필수로 들어가야 하며, 객체명은 Key 파라미터를 사용한다.

from pprint import pprint
import boto3

s3 = boto3.client("s3")
res = s3.get_object(Bucket="bucket-name", Key="sample.csv")

pprint(res)

 

위와 같이 객체 정보를 가져오는데, 실제 내용은 'Body'에 있고 utf-8로 디코딩 해주어야 한다.

 

만약 파일 내용을 확인하고 싶으면 아래와 같이 작성하면 된다.

from pprint import pprint
from io import StringIO
import boto3
import csv

s3 = boto3.client("s3")

res = s3.get_object(Bucket="ke-ivr-data", Key="sample.csv")
data = res["Body"].read().decode("utf-8")
reader = csv.DictReader(StringIO(data))

for idx, row in enumerate(reader):
    print(f"{idx}번째 row : {row}")

 

data를 출력해보면 파일의 내용을 알 수 있지만, 개인적으로 딕셔너리 형태를 선호하기에 DictReader를 자주 사용하는 편이다.

 

이렇게 읽어온 데이터를 DynamoDB에 넣어 주는 함수만 구현한다면, 하나씩 수동으로 DynamoDB 아이템을 생성하는 번거로움 없이

csv파일에 데이터를 정의해놓고 일괄로 DynamoDB에 넣어주는 프로그램을 만들 수 있다.

 

이런 식으로 boto3를 활용하면 aws 리소스 관리도 용이할 뿐더러 작업 시간을 매우 단축할 수 있다.