如何在python中使用boto3给定文件路径从s3下载文件

Ati*_*ska 8 python amazon-s3 boto3

非常基本,但我无法下载给定 s3 路径的文件。

例如,我有这个 s3://name1/name2/file_name.txt

import boto3
locations = ['s3://name1/name2/file_name.txt']
s3_client = boto3.client('s3')
bucket = 'name1'
prefix = 'name2'

for file in locations:
    s3_client.download_file(bucket, 'file_name.txt', 'my_local_folder')
Run Code Online (Sandbox Code Playgroud)

我收到错误 botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found

这个文件在我下载时存在。使用 aws cli 作为s3 path: s3://name1/name2/file_name.txt .

Bur*_*lid 11

您需要有一个文件名路径列表,然后修改您的代码,如文档中所示:

import os
import boto3
import botocore

files = ['name2/file_name.txt']

bucket = 'name1'

s3 = boto3.resource('s3')

for file in files:
   try:
       s3.Bucket(bucket).download_file(file, os.path.basename(file))
   except botocore.exceptions.ClientError as e:
       if e.response['Error']['Code'] == "404":
           print("The object does not exist.")
       else:
           raise
Run Code Online (Sandbox Code Playgroud)