Skip to content Skip to sidebar Skip to footer

Download A Binary File Using Python Requests Module

I need to download a file from an external source, I am using Basic authentication to login to the URL import requests response = requests.get('

Solution 1:

Working solution

import requests
import shutil

response = requests.get('<url>', auth=('<username>', '<password>'))
data = response.json()
html = data['list'][0]['attachments'][0]['url']
print (html)
data = requests.get('<url>', auth=('<username>', '<password>'), stream=True)
with open("C:/myfile.docx", 'wb') as f:
    data.raw.decode_content = True
    shutil.copyfileobj(data.raw, f) 

I am able to download the file as it is.

Solution 2:

When you want to download a file directly you can use shutil.copyfileobj():

https://docs.python.org/2/library/shutil.html#shutil.copyfileobj

You already are passing stream=True to requests which is what you need to get a file-like object back. Just pass that as the source to copyfileobj().

Post a Comment for "Download A Binary File Using Python Requests Module"