簡體   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