download_file_from_url

pyhelpers.ops.download_file_from_url(url, path_to_file, if_exists='replace', max_retries=5, random_header=True, verbose=False, requests_session_args=None, fake_headers_args=None, **kwargs)[source]

Download an object available at a valid URL.

See also [OPS-DFFU-1] and [OPS-DFFU-2].

Parameters:
  • url (str) – valid URL to a web resource

  • path_to_file (str | os.PathLike[str]) – a path where the downloaded object is saved as, or a filename

  • if_exists (str) – given that the specified file already exists, options include 'replace' (default, continuing to download the requested file and replace the existing one at the specified path) and 'pass' (cancelling the download)

  • max_retries (int) – maximum number of retries, defaults to 5

  • random_header (bool) – whether to go for a random agent, defaults to True

  • verbose (bool | int) – whether to print relevant information in console, defaults to False

  • requests_session_args (dict | None) – [optional] parameters of the function pyhelpers.ops.init_requests_session(), defaults to None

  • fake_headers_args (dict | None) – [optional] parameters of the function pyhelpers.ops.fake_requests_headers(), defaults to None

  • kwargs – [optional] parameters of requests.Session.get()

Examples:

>>> from pyhelpers.ops import download_file_from_url
>>> from pyhelpers.dirs import cd
>>> from PIL import Image
>>> import os

>>> logo_url = 'https://www.python.org/static/community_logos/python-logo-master-v3-TM.png'
>>> path_to_img = cd("tests\images", "ops-download_file_from_url-demo.png")

>>> # Check if "python-logo.png" exists at the specified path
>>> os.path.exists(path_to_img)
False

>>> # Download the .png file
>>> download_file_from_url(logo_url, path_to_img)

>>> # If download is successful, check again:
>>> os.path.exists(path_to_img)
True

>>> img = Image.open(path_to_img)
>>> img.show()  # as illustrated below
../_images/ops-download_file_from_url-demo.svg

Fig. 6 The Python Logo.


Note

  • When verbose=True, the function requires tqdm.