【问题标题】:How to upload a .pptx using pptx, io and boto3 in python?如何在 python 中使用 pptx、io 和 boto3 上传 .pptx?
【发布时间】:2021-02-25 05:35:35
【问题描述】:

我使用了对this question 的回复,以便使用 boto3 和 io 从 s3 读取 .pptx(模板)。我更新了 .pptx,现在想用新名称将其上传回 s3。

我看到 boto3 有一个 method to upload a file-like object to s3: upload_fileobj()

所以这就是我在尝试保存文件时正在做的事情:

import io
import boto3

from pptx import Presentation

s3 = boto3.client('s3')
s3_response_object = s3.get_object(Bucket='bucket', Key='file.pptx')
object_content = s3_response_object['Body'].read()

prs = Presentation(io.BytesIO(object_content))

# Do some stuff to the PowerPoint

out = io.BytesIO() # to have the presentation in binary format
with open(prs.save(out), "rb") as f:
    s3.upload_fileobj(f, 'BUCKET', 'KEY')

但我得到了错误

TypeError                                 Traceback (most recent call last)
<ipython-input-8-1956d13a7556> in <module>
----> 1 with open(prs.save(out), "rb") as f:
      2     s3.upload_fileobj(f, 'BUCKET', 'KEY')

TypeError: expected

 str, bytes or os.PathLike object, not NoneType

鉴于我从 Presentation 对象开始,我如何将其上传到 s3?

【问题讨论】:

    标签: python amazon-s3 io boto3 python-pptx


    【解决方案1】:

    试试这个:

    import io
    import boto3
    
    from pptx import Presentation
    
    s3 = boto3.client('s3')
    s3_response_object = s3.get_object(Bucket='bucket', Key='file.pptx')
    object_content = s3_response_object['Body'].read()
    
    prs = Presentation(io.BytesIO(object_content))
    
    # Do some stuff to the PowerPoint
    
    with io.BytesIO() as out:
        prs.save(out)
        out.seek(0)
        s3.upload_fileobj(out, 'BUCKET', 'KEY')
    

    【讨论】:

    • 非常感谢!它有效(在您第一次编辑之前和之后)!现在看起来很简单,你给了我正确的方法。
    • Np :) 后一种效果更好,因为 with 块在退出时自动关闭 IO 流。
    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2021-02-24
    • 2019-02-03
    相关资源
    最近更新 更多