File tree Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -56,12 +56,20 @@ The simplest way to use urllib.request is as follows::
56
56
with urllib.request.urlopen('http://python.org/') as response:
57
57
html = response.read()
58
58
59
- If you wish to retrieve a resource via URL and store it in a temporary location,
60
- you can do so via the :func: `~urllib.request.urlretrieve ` function::
59
+ If you wish to retrieve a resource via URL and store it in a temporary
60
+ location, you can do so via the :func: `shutil.copyfileobj ` and
61
+ :func: `tempfile.NamedTemporaryFile ` functions::
61
62
63
+ import shutil
64
+ import tempfile
62
65
import urllib.request
63
- local_filename, headers = urllib.request.urlretrieve('http://python.org/')
64
- html = open(local_filename)
66
+
67
+ with urllib.request.urlopen('http://python.org/') as response:
68
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
69
+ shutil.copyfileobj(response, tmp_file)
70
+
71
+ with open(tmp_file.name) as html:
72
+ pass
65
73
66
74
Many uses of urllib will be that simple (note that instead of an 'http:' URL we
67
75
could have used a URL starting with 'ftp:', 'file:', etc.). However, it's the
You can’t perform that action at this time.
0 commit comments