如何使用 boto3 下载该文件夹中的所有内容

kws*_*314 2 python amazon-s3 amazon-web-services boto3

我想下载 s3 文件夹中存在的所有 csv 文件(2021-02-15)。我尝试了以下操作,但失败了。我该怎么做?

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('bucket')
key = 'product/myproject/2021-02-15/'
objs = list(bucket.objects.filter(Prefix=key))
for obj in objs:
    client = boto3.client('s3')
    client.download_file(bucket, obj, obj)
Run Code Online (Sandbox Code Playgroud)

valueError: Filename must be a string

Mar*_*ani 6

Marcin 的答案是正确的,但不同路径中具有相同名称的文件将被覆盖。您可以通过在本地复制 S3 存储桶的文件夹结构来避免这种情况。

import boto3
import os
from pathlib import Path

s3 = boto3.resource('s3')

bucket = s3.Bucket('bucket')

key = 'product/myproject/2021-02-15/'
objs = list(bucket.objects.filter(Prefix=key))

for obj in objs:
    # print(obj.key)

    # remove the file name from the object key
    obj_path = os.path.dirname(obj.key)

    # create nested directory structure
    Path(obj_path).mkdir(parents=True, exist_ok=True)

    # save file with full path locally
    bucket.download_file(obj.key, obj.key)
Run Code Online (Sandbox Code Playgroud)