Download Files with Python (8 lines only!)

In this tutorial, I'll show you how to Download Files with 8 lines of python code. To do so, you need a package called requests{code}. You can install it using pip install requests{code} or pip3 install requests{code}

{tocify}

Step 1: Import functions

We need to import get{code} function from requests module.

from requests import get{codeBox}

Step 2: Connect to download host

We'll use get function to connect to the host and download it. The first argument of get function is the url.

url='https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-large-zip-file.zip'
resp=get(url, stream=True){codeBox}
Here we used stream=True{code} because, It's a file. If we don't use this, the file will be downloaded first and then we will able to write that data in file.

Step 3: Write data in a file

I don't think you need explanation for this step. Anyway, we will use open().write(){code} function to write all data in a file.

filename='output.zip'
open(filename, 'wb').write(resp.content)
print('Done'){codeBox}

Full Code

from requests import get

url='https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-large-zip-file.zip'
resp=get(url, stream=True)
filename='output.zip'
open(filename, 'wb').write(resp.content)
print('Done'){codeBox}

Post a Comment

Previous Post Next Post