简短答案:
使用Delimiter='/'
。这样可以避免对存储桶进行递归列出。这里的一些答案错误地建议进行完整列表并使用一些字符串操作来检索目录名称。这可能是非常低效的。请记住,S3实际上对存储桶可以包含的对象数量没有限制。因此,想象一下,在bar/
和之间foo/
,您有一万亿个对象:您将等待很长时间才能获得['bar/', 'foo/']
。
使用Paginators
。出于相同的原因(S3是工程师对无穷大的近似值),必须逐页列出,并避免将所有列表存储在内存中。而是将您的“侦听器”视为迭代器,并处理其产生的流。
使用boto3.client
,而不是boto3.resource
。该resource
版本似乎不能很好地处理该Delimiter
选项。如果您有资源,说a bucket = boto3.resource('s3').Bucket(name)
,则可以通过以下方式获取相应的客户端bucket.meta.client
。
长答案:
以下是我用于简单存储桶的迭代器(无版本处理)。
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(name)
# iterate through all S3 objects under some dir
>>> for p in s3ls(bucket, 'some/dir'):
... print(p)
# iterate through up to 20 S3 objects under some dir, starting with foo_0010
>>> for p in s3ls(bucket, 'some/dir', limit=20, start='foo_0010'):
... print(p)
# non-recursive listing under some dir:
>>> for p in s3ls(bucket, 'some/dir', recursive=False):
... print(p)
# non-recursive listing under some dir, listing only dirs:
>>> for p in s3ls(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
通过对上面给出的代码进行一点点s3list
检查,以检查来自的响应paginator
,您可以观察到一些有趣的事实:
该Marker
是真的排斥。GivenMarker=topdir + 'mixed/0500_foo_a'
将使列表从该键之后开始(根据AmazonS3 API),即使用.../mixed/0500_foo_b
。这就是的原因__prev_str()
。
Delimiter
列出时mixed/
,使用,每个响应都paginator
包含666个键和334个公共前缀。它很擅长不做出巨大的回应。
相反,在列出时dirs/
,来自的每个响应都paginator
包含1000个公共前缀(且没有键)。
以限制形式传递PaginationConfig={'MaxItems': limit}
限制仅限制键的数量,而不限制公共前缀。我们通过进一步截断迭代器流来解决这个问题。