Download a file with Python

Preparation

Activate your virtual environment and install requests with the command

python3 -m pip install requests

Inspect the list of installed modules

python3 -m pip list

Package Version ---------- --------- certifi 2020.6.20 chardet 3.0.4 idna 2.10 pip 20.2.3 requests 2.24.0 setuptools 50.3.1 urllib3 1.25.10 wheel 0.35.1

requests pulls in requests, certifi, chardet, idna, urllib3

You can check where requests was installed in this environment with the command

python3 -m pip show requests

Name: requests Version: 2.24.0 Summary: Python HTTP for Humans. Home-page: https://requests.readthedocs.io Author: Kenneth Reitz Author-email: me@kennethreitz.org License: Apache 2.0 Location: /home/andrei/python/virtualenvs/answerit_env/lib/python3.8/site-packages Requires: certifi, chardet, urllib3, idna Required-by:

Create the file download_demo.py

import requests url = 'http://some_url' r = requests.get(url) with open('file_name', 'wb') as f: f.write(r.content)

Run the script with the command

python3 download_demo.py

A file with the required content should appear

Article author: Andrei Olegovich

Banner image