【问题标题】:S3 Python List nested sub directoriesS3 Python列出嵌套的子目录
【发布时间】:2019-02-11 06:23:30
【问题描述】:

如何使用 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

【问题讨论】:

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


    【解决方案1】:

    文件夹/子目录实际上并不存在于 S3 中。相反,它们构成了对象文件名 (Key) 的一部分。

    因此,只需将 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

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多