简短回答:
使用Delimiter='/'
。这避免了对存储桶进行递归列出。在此处的某些答案错误地建议列出全部内容并使用某些字符串操作来检索目录名称。这可能非常低效。请记住,S3对存储桶中包含的对象数量几乎没有限制。因此,假设在bar /
和foo /
之间有一万亿个对象:您将等待很长时间才能获取['bar /', 'foo /']
。
使用Paginators
。出于同样的原因(S3是工程师对无限的近似),您必须通过页面进行列表,并避免将所有列表存储在内存中。相反,将您的“lister”视为迭代器,并处理其生成的流。
使用boto3.client
,而不是boto3.resource
。 resource
版本似乎无法很好地处理Delimiter
选项。如果您有一个资源,比如bucket = boto3.resource('s3').Bucket(name)
,则可以使用以下命令获取相应的客户端:bucket.meta.client
。
长回答:
以下是我用于简单桶(无版本处理)的迭代器。
import os
import boto3
from collections import namedtuple
from operator import attrgetter
S3Obj = namedtuple('S3Obj', ['key', 'mtime', 'size', 'ETag'])
def s3list(bucket, path, start=None, end=None, recursive=True, list_dirs=True,
list_objs=True, limit=None):
"""
Iterator that lists a bucket's objects under path, (optionally) starting with
start and ending before end.
If recursive is False, then list only the "depth=0" items (dirs and objects).
If recursive is True, then list recursively all objects (no dirs).
Args:
bucket:
a boto3.resource('s3').Bucket().
path:
a directory in the bucket.
start:
optional: start key, inclusive (may be a relative path under path, or
absolute in the bucket)
end:
optional: stop key, exclusive (may be a relative path under path, or
absolute in the bucket)
recursive:
optional, default True. If True, lists only objects. If False, lists
only depth 0 "directories" and objects.
list_dirs:
optional, default True. Has no effect in recursive listing. On
non-recursive listing, if False, then directories are omitted.
list_objs:
optional, default True. If False, then directories are omitted.
limit:
optional. If specified, then lists at most this many items.
Returns:
an iterator of S3Obj.
Examples:
# set up
>>> s3 = boto3.resource('s3')
... bucket = s3.Bucket('bucket-name')
# iterate through all S3 objects under some dir
>>> for p in s3list(bucket, 'some/dir'):
... print(p)
# iterate through up to 20 S3 objects under some dir, starting with foo_0010
>>> for p in s3list(bucket, 'some/dir', limit=20, start='foo_0010'):
... print(p)
# non-recursive listing under some dir:
>>> for p in s3list(bucket, 'some/dir', recursive=False):
... print(p)
# non-recursive listing under some dir, listing only dirs:
>>> for p in s3list(bucket, 'some/dir', recursive=False, list_objs=False):
... print(p)
"""
kwargs = dict()
if start is not None:
if not start.startswith(path):
start = os.path.join(path, start)
kwargs.update(Marker=__prev_str(start))
if end is not None:
if not end.startswith(path):
end = os.path.join(path, end)
if not recursive:
kwargs.update(Delimiter='/')
if not path.endswith('/'):
path += '/'
kwargs.update(Prefix=path)
if limit is not None:
kwargs.update(PaginationConfig={'MaxItems': limit})
paginator = bucket.meta.client.get_paginator('list_objects')
for resp in paginator.paginate(Bucket=bucket.name, **kwargs):
q = []
if 'CommonPrefixes' in resp and list_dirs:
q = [S3Obj(f['Prefix'], None, None, None) for f in resp['CommonPrefixes']]
if 'Contents' in resp and list_objs:
q += [S3Obj(f['Key'], f['LastModified'], f['Size'], f['ETag']) for f in resp['Contents']]
q = sorted(q, key=attrgetter('key'))
if limit is not None:
q = q[:limit]
limit -= len(q)
for p in q:
if end is not None and p.key >= end:
return
yield p
def __prev_str(s):
if len(s) == 0:
return s
s, c = s[:-1], ord(s[-1])
if c > 0:
s += chr(c - 1)
s += ''.join(['\u7FFF' for _ in range(10)])
return s
测试:
以下内容有助于测试paginator
和list_objects
的行为。它创建了许多文件夹和文件。由于每页最多可以容纳1000个条目,因此我们为文件夹和文件使用了该数字的倍数。dirs
仅包含目录(每个目录下有一个对象)。mixed
包含目录和对象的混合,每个目录下有2个对象(当然还有一个在目录下的对象;S3仅存储对象)。
import concurrent
def genkeys(top='tmp/test', n=2000):
for k in range(n):
if k % 100 == 0:
print(k)
for name in [
os.path.join(top, 'dirs', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_foo_a'),
os.path.join(top, 'mixed', f'{k:04d}_foo_b'),
]:
yield name
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
executor.map(lambda name: bucket.put_object(Key=name, Body='hi\n'.encode()), genkeys())
生成的结构如下:
./dirs/0000_dir/foo
./dirs/0001_dir/foo
./dirs/0002_dir/foo
...
./dirs/1999_dir/foo
./mixed/0000_dir/foo
./mixed/0000_foo_a
./mixed/0000_foo_b
./mixed/0001_dir/foo
./mixed/0001_foo_a
./mixed/0001_foo_b
./mixed/0002_dir/foo
./mixed/0002_foo_a
./mixed/0002_foo_b
...
./mixed/1999_dir/foo
./mixed/1999_foo_a
./mixed/1999_foo_b
稍微调整以上给出的代码以检查paginator
响应结果,你可以观察到一些有趣的事实:
Marker
真的很独特。给定Marker=topdir + 'mixed/0500_foo_a'
将使列表从该键之后开始(根据Amazon S3 API),即从.../mixed/0500_foo_b
开始。这就是__prev_str()
的原因。
使用Delimiter
列出mixed/
时,每个paginator
响应包含666个键和334个公共前缀。 它非常擅长不构建巨大的响应。
相比之下,列出dirs/
时,每个paginator
响应包含1000个公共前缀(没有键)。
传递限制形式的PaginationConfig={'MaxItems': limit}
仅限制键的数量,而不是公共前缀。 我们通过进一步截断迭代器的流来处理这个问题。
AttributeError:'S3'对象没有'Bucket'属性
。 - a zEnItH