all Python 3urllib.requestfunction
urllib.request.urlretrieve()
opening URLs
Downloads the object at a URL into a local file and returns a (filename, headers) pair. It is inherited from the Python 2 urllib module.
Syntax
filename, headers = urllib.request.urlretrieve(url, filename=None, reporthook=None)
The documentation files it under the legacy interface that may be deprecated, so new code is safer with urlopen() plus shutil.copyfileobj(). Without filename the data goes to a temporary file that is never removed on its own — urlcleanup() removes it. For a local file:// URL without filename nothing is copied at all: you get the path of the original file. If fewer bytes arrive than Content-Length promised, ContentTooShortError is raised.
Examples
import pathlib, urllib.request
src = pathlib.Path('src.txt')
src.write_text('data', encoding='utf-8')
name, headers = urllib.request.urlretrieve(src.resolve().as_uri(), 'copy.txt')
print(name, pathlib.Path(name).read_text(encoding='utf-8')) # → copy.txt data
print(headers['Content-length']) # → 4
import os, pathlib, urllib.request
name, _ = urllib.request.urlretrieve('data:,hello')
print(pathlib.Path(name).read_text()) # → hello
urllib.request.urlcleanup()
print(os.path.exists(name)) # → False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy