Python 如何使用boto3查看存储桶内路径的内容?
基于对bucket名称中包含句点()的问题的评论,区域似乎很重要,因此我想通过从已知bucket中获取Python 如何使用boto3查看存储桶内路径的内容?,python,amazon-s3,boto3,Python,Amazon S3,Boto3,基于对bucket名称中包含句点()的问题的评论,区域似乎很重要,因此我想通过从已知bucket中获取区域名称来从一开始就解决这个问题: import boto3 s3 = boto3.resource('s3') region = s3.meta.client.get_bucket_location(Bucket='some.topLevel.BucketPath.withPeriods')['LocationConstraint'] #set region in resource s3 =
区域名称来从一开始就解决这个问题:
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'
AttributeError回溯(最近一次调用)
在()
1 x=s3.Bucket('some.topLevel.BucketPath.withPeriods')
2对于x.objects.all()中的项:
---->3对于item.objects.all()中的对象:
4印刷品
AttributeError:'s3.ObjectSummary'对象没有属性'objects'
非常感谢您的帮助。您可以使用以下代码在一个存储桶中获取文件列表:
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)
返回的结果文件列表是此S3中包含的所有文件。您可以使用以下代码在一个存储桶中获取文件列表:
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)
返回的结果文件列表是此S3中包含的所有文件。Oh whoops-我以为您遇到了使用名称中带有句点的存储桶的问题(这是一个实际问题)。收回我的评论。此外,S3没有“子bucket”的概念(bucket本质上只是键名的平面列表)。听起来你真的只是想得到一个文件列表,而不需要/subdir1/subdir2/etc/etc/etc/etc的“虚拟路径”
?我基本上希望能够在路径的任何级别上拥有某种$ls
功能。谢谢你考虑这个问题。我也会收回我以前的评论。我投票重新打开这个,因为这个问题与副本无关,并提出了一个完全不同的问题。哦,哎呀-我以为你面临着在名称中使用带句点的桶的问题(这是一个实际问题)。收回我的评论。此外,S3没有“子bucket”的概念(bucket本质上只是键名的平面列表)。听起来你真的只是想得到一个文件列表,而不需要/subdir1/subdir2/etc/etc/etc/etc的“虚拟路径”
?我基本上希望能够在路径的任何级别上拥有某种$ls
功能。谢谢你考虑这个问题。我也会收回我以前的评论。我投票重新开始这个问题,因为这个问题与副本无关,而是问了一个完全不同的问题。