如何在 Python 中使用 boto3 将 Wasabi/S3 对象下载到文件

你可以使用 boto3 的 download_fileobj() 将文件从 S3 下载到本地文件系统:

download_fileobj.py
with open("myfile.txt", "wb") as outfile:
    my_bucket.download_fileobj("myfile.txt", outfile)

注意文件需要以二进制模式("wb")打开。

完整示例

download_boto3_example.py
import boto3

# 创建到 Wasabi / S3 的连接
s3 = boto3.resource('s3',
    endpoint_url = 'https://s3.eu-central-1.wasabisys.com',
    aws_access_key_id = 'MY_ACCESS_KEY',
    aws_secret_access_key = 'MY_SECRET_KEY'
)

# 获取 bucket 对象
my_bucket = s3.Bucket('boto-test')

# 下载远程对象 "myfile.txt" 到本地文件 "test.txt"
my_bucket.download_file("myfile.txt", "test.txt")

Don’t forget to fill in MY_ACCESS_KEY and MY_SECRET_KEY. Depending on what region and what S3-compatible service you use, you might need to use another endpoint URL instead of https://s3.eu-central-1.wasabisys.com.


Check out similar posts by category: Allgemein