栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Boto3从S3存储桶下载所有文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Boto3从S3存储桶下载所有文件

当使用具有1000多个对象的存储桶时,实现一个解决方案(使用

NextContinuationToken
最多1000个键的顺序集)是必要的。该解决方案首先编译对象列表,然后迭代创建指定目录并下载现有对象。

import boto3import oss3_client = boto3.client('s3')def download_dir(prefix, local, bucket, client=s3_client):    """    params:    - prefix: pattern to match in s3    - local: local path to folder in which to place files    - bucket: s3 bucket with target contents    - client: initialized s3 client object    """    keys = []    dirs = []    next_token = ''    base_kwargs = {        'Bucket':bucket,        'Prefix':prefix,    }    while next_token is not None:        kwargs = base_kwargs.copy()        if next_token != '': kwargs.update({'ContinuationToken': next_token})        results = client.list_objects_v2(**kwargs)        contents = results.get('Contents')        for i in contents: k = i.get('Key') if k[-1] != '/':     keys.append(k) else:     dirs.append(k)        next_token = results.get('NextContinuationToken')    for d in dirs:        dest_pathname = os.path.join(local, d)        if not os.path.exists(os.path.dirname(dest_pathname)): os.makedirs(os.path.dirname(dest_pathname))    for k in keys:        dest_pathname = os.path.join(local, k)        if not os.path.exists(os.path.dirname(dest_pathname)): os.makedirs(os.path.dirname(dest_pathname))        client.download_file(bucket, k, dest_pathname)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661548.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号