S3 Python列表嵌套子目录

时间:2019-02-11 06:23:31

标签: python-3.x amazon-web-services amazon-s3 boto3

如何使用boto3 python在S3存储桶的前缀中列出子目录?

例如,如果我有一个名为test的存储桶,其结构如下:

test/abc/def/1/a.gz
test/abc/def/2/b.gz
test/abc/ghi/1/a.gz

然后我希望输出为:

test/abc/def/1
test/abc/def/2
test/abc/ghi/1

1 个答案:

答案 0 :(得分:0)

文件夹/子目录在S3中实际上不存在。而是它们成为对象文件名(Key)的一部分。

因此,只需将密钥抓到最后一个斜杠即可:

import boto3

s3 = boto3.client('s3', region_name = 'ap-southeast-2')

response = s3.list_objects_v2(Bucket='my-bucket')

# If the Key contains a slash, store the Key up to the last slash
folders = set(object['Key'][:object['Key'].rfind('/')+1] for object in response['Contents'] if '/' in object['Key'])

# Print the results
print('\n'.join(sorted(folders)))

另请参阅:Determine if folder or file key - Boto