将文件从内存上传到 S3

Cia*_*ran 5 python amazon-s3 amazon-web-services boto3

我已经将一个 csv 文件从 S3 下载到内存中,并使用 Boto3 和 Python 编辑了该文件。如何在不将其存储在本地的情况下将该文件重新上传到 S3?

Joh*_*ein 6

根据@JamesMchugh,来自put_object()

response = client.put_object(
    Body=b'bytes'|file,
    Bucket='string',
    Key='string',
)
Run Code Online (Sandbox Code Playgroud)


Waq*_*Ali 5

就我而言,我有一个字典列表,我必须在内存文件中创建并将其保存在 S3 上。以下代码对我有用!

import csv
import boto3
from io import StringIO
# input list
list_of_dicts = [{'name': 'name 1', 'age': 25}, {'name': 'name 2', 'age': 26}, {'name': 'name 3', 'age': 27}]

# convert list of dicts to list of lists
file_data = []
header = list(list_of_dicts[0].keys())
file_data = [[d[key] for key in header] for d in list_of_dicts]
file_data = [header] + file_data

# create in memory file and write data to it.
file_to_save = StringIO()
csv.writer(file_to_save).writerows(file_data)
file_to_save = bytes(file_to_save.getvalue(), encoding='utf-8')
file_name_on_s3 = 'my_data.csv'

# save in memory file to S3
client = boto3.client('s3',
                      aws_access_key_id='your access key',
                      aws_secret_access_key='your secret key')
response = client.put_object(
    Body=file_to_save,
    Bucket='your bucket name',
    Key=file_name_on_s3,
)
Run Code Online (Sandbox Code Playgroud)