簡體   English   中英

urllib.request.urlretrieve 如果不返回會做什么

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM