技術雑記帳兼日記帳

AWS、Python、Terraformの使い方をコッソリ

Amazon S3 and boto3

忘れそうなのでメモついでにAWS CLIPythonでS3の使い方をまとめる。

docs.aws.amazon.com

S3の設定

aws s3 mb s3://バケット名
aws s3 sync images s3://バケット名/images/
aws s3 rm  s3://バケット名/ --include 'img*.jpg' --recursive --dryrun
でためして
aws s3 rm  s3://バケット名/ --include 'img*.jpg' --recursive
aws s3 ls s3://バケット名/images/

バケットを作るときに以下のNGが出た場合はAWS内で重複しているのでバケット名を替える必要がある

make_bucket failed: s3://imagebucket An error occurred (BucketAlreadyExists) when calling the CreateBucket operation: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.

「/」のつけ忘れでフォルダ、ファイルが混同するので注意が必要

最後にpythonでimg-catの中身をS3に転送して結果をCSVに出力するプログラムを書いてみた。

import boto3, pathlib 

s3 = boto3.client('s3')

files = pathlib.Path('img-cat/').glob('*.jpg')
for file in files:
    s3.upload_file('img-cat/'+ file.name, 'バケット名', 'img-cat/' + file.name)

objs = s3.list_objects_v2(Bucket='バケット名')
csv = '{},{}\n'.format('file', 'size')

for o in objs.get('Contents'):
    key = o.get('Key')
    size = o.get('Size')
    if key[-4:]=='.jpg':
        csv += '{},{}\n'.format(key, int(size))

f = open('uplist.csv', 'w')
f.write(csv)

AWS CLIとboto3を使いこなして幸せになりたいな。