我如何能看到什么是在S3桶与boto3?(例如,写一个“ls”)?
做以下事情:
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('some/path/')
返回:
s3.Bucket(name='some/path/')
我如何看到它的内容?
我如何能看到什么是在S3桶与boto3?(例如,写一个“ls”)?
做以下事情:
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('some/path/')
返回:
s3.Bucket(name='some/path/')
我如何看到它的内容?
当前回答
也可以这样做:
csv_files = s3.list_objects_v2(s3_bucket_path)
for obj in csv_files['Contents']:
key = obj['Key']
其他回答
import boto3
s3 = boto3.resource('s3')
## Bucket to use
my_bucket = s3.Bucket('city-bucket')
## List objects within a given prefix
for obj in my_bucket.objects.filter(Delimiter='/', Prefix='city/'):
print obj.key
输出:
city/pune.csv
city/goa.csv
我以前是这样做的:
import boto3
s3 = boto3.resource('s3')
bucket=s3.Bucket("bucket_name")
contents = [_.key for _ in bucket.objects.all() if "subfolders/ifany/" in _.key]
首先,创建一个s3客户端对象:
s3_client = boto3.client('s3')
接下来,创建一个变量来保存bucket名称和文件夹。注意文件夹名后面的斜杠“/”:
bucket_name = 'my-bucket'
folder = 'some-folder/'
接下来,调用s3_client。List_objects_v2获取文件夹内容对象的元数据:
response = s3_client.list_objects_v2(
Bucket=bucket_name,
Prefix=folder
)
最后,使用对象的元数据,您可以通过调用s3_client来获取S3对象。get_object功能:
for object_metadata in response['Contents']:
object_key = object_metadata['Key']
response = s3_client.get_object(
Bucket=bucket_name,
Key=object_key
)
object_body = response['Body'].read()
print(object_body)
如你所见,字符串格式的对象内容可以通过调用response['Body'].read()来获得。
我的s3键实用函数本质上是@Hephaestus的答案的优化版本:
import boto3
s3_paginator = boto3.client('s3').get_paginator('list_objects_v2')
def keys(bucket_name, prefix='/', delimiter='/', start_after=''):
prefix = prefix.lstrip(delimiter)
start_after = (start_after or prefix) if prefix.endswith(delimiter) else start_after
for page in s3_paginator.paginate(Bucket=bucket_name, Prefix=prefix, StartAfter=start_after):
for content in page.get('Contents', ()):
yield content['Key']
在我的测试(boto3 1.9.84)中,它比等效的(但更简单)代码要快得多:
import boto3
def keys(bucket_name, prefix='/', delimiter='/'):
prefix = prefix.lstrip(delimiter)
bucket = boto3.resource('s3').Bucket(bucket_name)
return (_.key for _ in bucket.objects.filter(Prefix=prefix))
由于S3保证UTF-8二进制排序结果,因此在第一个函数中添加了start_after优化。
查看内容的一种方法是:
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object)