[英]What does urllib.request.urlretrieve do if not returned
从 python 文档中提到, urllib.request.urlretrieve
返回一个元组,将用于打开文件,如下面的代码-A 所示。
但是在示例代码-B 中。 urllib.request.urlretrieve
不会返回,但没有它,代码将失败。 请帮助澄清urllib.request.urlretrieve
在代码 B 中的作用。谢谢
代码 A
import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()
代码 B
import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing") # datasets\housing
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if not os.path.isdir(housing_path):
os.makedirs(housing_path)
tgz_path = os.path.join(housing_path, "housing.tgz") #datasets\housing\housing.tgz
urllib.request.urlretrieve(housing_url, tgz_path) #what does this code here do?
housing_tgz = tarfile.open(tgz_path)
housing_tgz.extractall(path=housing_path)
housing_tgz.close()
在第二个代码中,通过指定filename
,这将自动将内容保存在本地定义的路径中。 在这种情况下,这是tgz_path
。
我不确定你所说的失败是什么意思。 总是返回一个元组。 问题是它是否存储在 memory 中。 例如,以下内容仍然有效:
In [1]: import urllib.request
In [2]: urllib.request.urlretrieve('http://python.org/', 'test.python')
Out[2]: ('test.python', <http.client.HTTPMessage at 0x108d22390>)
The retrieve() method is used to save web content from url (eg csv,images etc) In your case it is saving the housing data saved up in the url. 您可以查看文档 [此处][1]
tgz_path = os.path.join(housing_path, "housing.tgz") #<--- is the path directory
# takes 2 parameters the url and the file path to save the content
urllib.request.urlretrieve( housing_url, tgz_path)
[1]: https://docs.python.org/3/library/urllib.request.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.