繁体   English   中英

python中的boto3文件上传

[英]boto3 file upload in python

我正在尝试通过 boto 3 在 aws s3 存储桶中上传文件

但正在上传以下文件<_io.TextIOWrapper name='excel.csv' mode='a' encoding='UTF-8'>

def write_csv(data):
    with open('excel.csv', 'a') as file:
        writer = csv.writer(file)
        writer.writerow([data['account_id'],
                         data['country'],
                         data['end_date'],
                         data['start_date']])

    uploadtos3(str(file))


def uploadtos3(file):
    key = 'xxxx'
    seckey = 'xxxx'
    s3 = boto3.resource(  's3',
                           aws_access_key_id = key,
                           aws_secret_access_key = seckey)
    upload_file_bucket = 'apiuploadtest'
    s3.Object(upload_file_bucket,str(file)).put(Body = str(file))

如何正确上传文件?

Bodyput方法中的Object是:

正文(字节或类似 object 的可搜索文件)—— Object 数据。

因此,应该尝试以下方法(固定缩进并删除str ):

def write_csv(data):
    with open('excel.csv', 'a') as file:
        writer = csv.writer(file)
        writer.writerow([data['account_id'],
                         data['country'],
                         data['end_date'],
                         data['start_date']])

        uploadtos3(file)


def uploadtos3(file):
    key = 'xxxx'
    seckey = 'xxxx'
    s3 = boto3.resource('s3',
                         aws_access_key_id = key,
                         aws_secret_access_key = seckey)
    upload_file_bucket = 'apiuploadtest'
    s3.Object(upload_file_bucket, <key-name-on-s3>).put(Body = file)

顺便说一句,在您的源代码中硬编码任何 AWS 凭证不是一个好习惯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM