大前提として

AWS S3はkey-value型のストレージであり、基本的にはディレクトリなどの階層的な概念がない。aws-cliなどではS3を擬似階層的に使用できるが、boto3はkeyに対応するobjectを取得という形が基本であるので、PrefixとDellimiterをうまく使いS3を階層的に使う。
https://hacknote.jp/archives/20100/

ということを意識しつつ、我々に見えてる擬似的なディレクトリ一覧を取得したい時がある。

その際、上のリンクのコードはそのまま動かなかったので修正版を

ちなみにバージョンによっては上のリンク先のコードが動くのかも。

今回の実行環境は

pip show boto3

Name: boto3
Version: 1.20.8
Summary: The AWS SDK for Python
Home-page: https://github.com/boto/boto3
Author: Amazon Web Services
Author-email: None
License: Apache License 2.0
Location: /Users/hogefuga/opt/anaconda3/lib/python3.8/site-packages
Requires: s3transfer, botocore, jmespath
Required-by: 

という感じです

import boto3

s3 = boto3.client('s3')
result = s3.list_objects(Bucket='バケット名', Prefix='test_prefix/', Delimiter='/')
for o in result.get('CommonPrefixes'):
    print(o.get('Prefix'))

Prefixを任意の階層の深さまで指定してあげると、boto3を使ってs3の任意の階層のディレクトリ(もどき)の一覧を取ってくることができる

test_prefix/2021-01/
test_prefix/2021-02/
test_prefix/2021-03/
test_prefix/2021-04/
test_prefix/2021-05/
test_prefix/2021-06/
test_prefix/2021-07/
test_prefix/2021-08/
test_prefix/2021-09/
test_prefix/2021-10/
test_prefix/2021-11/
test_prefix/2021-12/
test_prefix/2022-01/
test_prefix/2022-02/
test_prefix/2022-03/
test_prefix/2022-04/
test_prefix/2022-05/
test_prefix/2022-06/
test_prefix/2022-07/
test_prefix/2022-08/
test_prefix/2022-09/
test_prefix/2022-10/
test_prefix/2022-11/
test_prefix/2022-12/