개요
- boto3를 이용해서 s3 사용하는 몇 가지 기본 패턴을 정리해둔다.
s3 오브젝트 목록 조회
- 특정 버킷안의 파일목록을 조회한다.
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('BUCKET_NAME')
# list object
for obj in bucket.objects.all():
print(obj.key)
파일 다운로드
형식은 다음과 같다.
S3.Client.download_file(Bucket, Key, Filename, ExtraArgs=None, Callback=None, Config=None)
- Key는 다운로드받고자 하는 파일명 (The name of the key to download from.)
- Filename은 로컬의 파일저장 경로이다. (The path to the file to download to.)
예를 들면 다음과 같이 작성한다.
import boto3
s3 = boto3.resource('s3')
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
파일 업로드
형식은 다음과 같다.
S3.Client.upload_file(Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None)
- Filename은 업로드하고자 하는 로컬 파일의 경로 (The path to the file to upload.)
- Key는 업로드하고 싶은 파일명 (The name of the key to upload to.)
import boto3
s3 = boto3.client('s3')
s3.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
참고로 폴더를 만들면서 업로드하고 싶으면 다음과 같이 한다.
my_folder
라는 이름의 폴더가 만들어지고 그 하위에 hello.txt가 업로드된다.
import boto3
s3 = boto3.client('s3')
s3.upload_file('/tmp/hello.txt', 'mybucket', 'my_folder/hello.txt')
오브젝트 업로드
- 로컬에 저장된 파일을 업로드하는 것이 아니라 프로그램 내부에서 오브젝트를 그대로 업로드하고 싶은 경우도 있다.
- 예를들면 파이썬 프로그램 내에서 맵 객체를 JSON타입으로 덤프해서 파일로 업로드하고 싶은 경우이다.
import json
import boto3
s3 = boto3.client('s3')
json_object = 'your_json_object here'
s3.put_object(
Body=json.dumps(json_object),
Bucket='your_bucket_name',
Key='your_key_here'
)
참고
- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#s3
- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/download_file.html
- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/upload_file.html
- https://stackoverflow.com/questions/46844263/writing-json-to-file-in-s3-bucket