用boto3列出桶中的内容

2024-03-29 08:11:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用boto3查看S3中的bucket中的内容?(即做一个"ls")?

执行以下操作:

import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('some/path/')

返回:

s3.Bucket(name='some/path/')

我怎么看里面的东西?


Tags: pathnameimport内容s3bucketmysome
3条回答

这类似于“ls”,但它不考虑前缀文件夹约定,并将列出bucket中的对象。它留给读者过滤掉作为键名一部分的前缀。

在Python 2中:

from boto.s3.connection import S3Connection

conn = S3Connection() # assumes boto.cfg setup
bucket = conn.get_bucket('bucket_name')
for obj in bucket.get_all_keys():
    print(obj.key)

在Python 3中:

from boto3 import client

conn = client('s3')  # again assumes boto.cfg setup, assume AWS S3
for key in conn.list_objects(Bucket='bucket_name')['Contents']:
    print(key['Key'])

我假设您已经分别配置了身份验证。

import boto3
s3 = boto3.resource('s3')

my_bucket = s3.Bucket('bucket_name')

for file in my_bucket.objects.all():
    print(file.key)

查看内容的一种方法是:

for my_bucket_object in my_bucket.objects.all():
    print(my_bucket_object)

相关问题 更多 >