【发布时间】:2021-07-30 15:09:57
【问题描述】:
我知道在 SO 上提出了很多类似的问题(尤其是 this),但没有一个答案能真正解决我的情况。当然,我知道 S3 中没有文件夹之类的东西。在内部,所有内容都存储为密钥。
我有以下目录结构;
TWEAKS/date=2020-03-19/hour=20/file.gzip
TWEAKS/date=2020-03-20/hour=21/file.gzip
TWEAKS/date=2020-03-21/hour=22/file.gzip
TWEAKS/date=2020-03-22/hour=23/file.gzip
我试过了;
def list_folders(s3_client, bucket_name):
response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix='TWEAKS/', Delimiter='/')
for content in response.get('CommonPrefixes', []):
yield content.get('Prefix')
s3_client = session.client('s3')
folder_list = list_folders(s3_client, bucket_name)
for folder in folder_list:
print('Folder found: %s' % folder)
但这只会列出第一级之前的所有目录
Folder found: TWEAKS/date=2020-03-19/
Folder found: TWEAKS/date=2020-03-20/
Folder found: TWEAKS/date=2020-03-21/
Folder found: TWEAKS/date=2020-03-22/
现在我无法将子目录添加到前缀中,因为名称不同 hour=21、hour=22 ... 有没有办法实现此输出?
Folder found: TWEAKS/date=2020-03-19/hour=20/
Folder found: TWEAKS/date=2020-03-20/hour=21/
Folder found: TWEAKS/date=2020-03-21/hour=22/
Folder found: TWEAKS/date=2020-03-22/hour=23/
【问题讨论】:
-
您需要递归查看每个
CommonPrefix,将CommonPrefix 作为新的Prefix传递,然后使用新的CommonPrefixes 列表。坦率地说,列出所有对象然后解析字符串会更容易,因为它需要最少的 API 调用。如果您的存储桶很大,那么您可以考虑使用Amazon S3 Inventory 获取存储桶内容的每日 CSV 文件。
标签: python amazon-web-services amazon-s3 boto3