Python boto3 AWS S3 指定バケット上のフォルダ一覧を取得する方法

環境
AWS CLI
Python3.9
AWS S3

操作方法
1.pythonのboto3をインストールします。
pip install boto3

2.pythonファイルを作成します(bucket_list.py)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import boto3
from boto3.session import Session
def list(prefix):
result = client.list_objects(Bucket=bucket.name, Prefix=prefix, Delimiter='/')
objects = result.get('CommonPrefixes')
if objects:
for object in objects:
prefix = object.get('Prefix')
print(prefix)
list(prefix)
return
PROFILE_NAME = 'プロファイル名'
session = Session(profile_name=PROFILE_NAME)
s3 = session.resource('s3')
AWS_S3_BUCKET_NAME = 'arkgame-bucket'
bucket = s3.Bucket(AWS_S3_BUCKET_NAME)
client = bucket.meta.client
list('')
import boto3 from boto3.session import Session def list(prefix): result = client.list_objects(Bucket=bucket.name, Prefix=prefix, Delimiter='/') objects = result.get('CommonPrefixes') if objects: for object in objects: prefix = object.get('Prefix') print(prefix) list(prefix) return PROFILE_NAME = 'プロファイル名' session = Session(profile_name=PROFILE_NAME) s3 = session.resource('s3') AWS_S3_BUCKET_NAME = 'arkgame-bucket' bucket = s3.Bucket(AWS_S3_BUCKET_NAME) client = bucket.meta.client list('')
import boto3
from boto3.session import Session

def list(prefix):
    result = client.list_objects(Bucket=bucket.name, Prefix=prefix, Delimiter='/')
    objects = result.get('CommonPrefixes')

    if objects:
        for object in objects:
            prefix = object.get('Prefix')
            print(prefix)
            list(prefix)
    return

PROFILE_NAME = 'プロファイル名'
session = Session(profile_name=PROFILE_NAME)
s3 = session.resource('s3')

AWS_S3_BUCKET_NAME = 'arkgame-bucket'
bucket = s3.Bucket(AWS_S3_BUCKET_NAME)
client = bucket.meta.client
list('')

実行結果
$ python bucket_list.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sync/
sync/dir1/
sync/dir1/dir1_1/
sync/dir1/dir1_2/
sync/ sync/dir1/ sync/dir1/dir1_1/ sync/dir1/dir1_2/
sync/
sync/dir1/
sync/dir1/dir1_1/
sync/dir1/dir1_2/

 

IT

Posted by arkgame