Search code examples
pythonamazon-web-servicesamazon-s3python-docx

How to save .docx file into S3?


I am using python-docx to create document. I want to save this file to AWS S3. Currently what I am doing is, I am creating .docx file and saving it locally using document.save('filename.docx'). Then using s3.meta.client.upload_file('/path/to/file/filename.docx', bucket, 'filename.docx') to save it into S3. Is there any way where I can save .docx file directly into AWS S3 without saving it locally?


Solution

  • Yes, you can. As @ewong suggested, here is a sample code snippet:

    import boto3
    from io import BytesIO
    from docx import Document
    
    s3 = boto3.client('s3')
    document = Document()
    # ...
    
    with BytesIO() as fileobj:
        document.save(fileobj)
        fileobj.seek(0)
        s3.upload_fileobj(fileobj, 'your-bucket-name', 'your/s3/key')