【问题标题】:How to use boto3 to view contents of a path within a bucket?如何使用 boto3 查看存储桶内路径的内容?
【发布时间】:2019-03-20 17:12:13
【问题描述】:

根据 cmets 关于包含句点的存储桶名称 (example) 的问题,该区域似乎很重要,因此我想从一开始就通过从已知存储桶中获取 region_name 来解决该问题:

import boto3
s3 = boto3.resource('s3')
region = s3.meta.client.get_bucket_location(Bucket='some.topLevel.BucketPath.withPeriods')['LocationConstraint']
#set region in resource
s3 = boto3.resource('s3',region_name=region)

要查看顶层的所有存储桶:

for bucket in s3.buckets.all():
    print(bucket.name)

如果我们想查看 'some.topLevel.BucketPath.withPeriods' 的内容:

x = s3.Bucket('some.topLevel.BucketPath.withPeriods')
for item in x.objects.all():
    print item

以下还应提供信息:

s3.meta.client.head_bucket(Bucket='some.topLevel.BucketPath.withPeriods')
s3.meta.client.get_bucket_acl(Bucket='some.topLevel.BucketPath.withPeriods')

要将一些测试文件上传到适当的存储桶:

with open ('~/someFile.pdf', 'rb') as data:
    s3.meta.client.put_object(Bucket='some.topLevel.BucketPath.withPeriods',Key='s3SubDir1/s3SubDir2/someTestFile1.pdf', Body=data)


with open ('~/someFile.pdf', 'rb') as data:
    s3.Bucket('some.topLevel.BucketPath.withPeriods').put_object(Key='s3SubDir1/s3SubDir2/someTestFile2.pdf', Body=data)

问题:
1、如何查看路径some.topLevel.BucketPath.withPeriods/s3SubDir1/s3SubDir2/的内容?

我从这条路开始:

x = s3.Bucket('some.topLevel.BucketPath.withPeriods')
for item in x.objects.all():
    for thing in item.objects.all():
        print thing 

错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-38-bc4079ea1f49> in <module>()
      1 x = s3.Bucket('some.topLevel.BucketPath.withPeriods')
      2 for item in x.objects.all():
----> 3     for thing in item.objects.all():
      4         print thing

AttributeError: 's3.ObjectSummary' object has no attribute 'objects'

非常感谢任何帮助。

【问题讨论】:

  • 哦,哎呀-我以为您遇到了使用名称中带有句点的存储桶的问题(这是一个实际问题)。撤回我的评论。此外,S3 没有“子存储桶”的概念(存储桶本质上只是键名的平面列表)。 听起来你真的只是想获得一个没有/subdir1/subdir2/etc/etc/etc'虚拟路径'的文件列表?
  • 我基本上希望能够在路径的任何级别拥有某种$ ls 功能。感谢您考虑这个问题。我也会收回我之前的评论。
  • 我投票决定重新打开这个问题,因为这个问题与副本无关,并且完全提出了一个不同的问题。

标签: python amazon-s3 boto3


【解决方案1】:

您可以使用以下代码获取一个存储桶中的文件列表:

file_list = []
for file in my_bucket.objects.all():
    # you can also get what type file you want
    if file.key.endswith('.docx'):
         file_list.append(file.key)

返回的结果file_list就是这个S3中包含的所有文件。

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 2022-06-12
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多