Amazon boto3 download file from S3 to tempfile

Viewed 5017

Python has the ability to create a tempfile as a context manager. Rather than having to make a directory myself, along with the path, and then cleaning it up when done, it would be better to use this tempfile.

Is there any support in the boto3 client to download, from s3, to a tempfile?

1 Answers

Try the download_fileobj method which accepts a file-like object and requires binary mode, for example:

import boto3
import tempfile

s3 = boto3.client('s3')

with tempfile.TemporaryFile(mode='w+b') as f:
    s3.download_fileobj('mybucket', 'mykey', f)
Related