在 Mac os X 上使用 tarfile 打开 .tgz 文件

Opening .tgz files with tarfile on Mac os X

我正在学习《Hine Learning with Scikit-Learn and TensorFlow》一书 Machine Learning with Scikit-Learn and TensorFlow,在第一个项目中,您可能知道,它将处理住房数据集。

当我想用 tarfile 打开 housing.tgz 时,出现错误:ReadError: file could not be opened successfully.

我是 Mac OS 用户,我搜索了很多。但是无论如何我都找不到解决这个问题的方法。即使我尝试了 [this question][1] 中的解决方案,但它没有用。 Mac 似乎无法打开 .tgz 文件。有大神帮忙吗?(我把书上的代码都抄下来了,代码没问题)

提前致谢!

我的代码:

import os
import tarfile
from six.moves import urllib

DOWNLOAD_ROOT = "https://github.com/ageron/handson-ml2/tree/master/"
HOUSING_PATH = os.path.join("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)
    # os.makedirs(housing_path, exist_ok=True)
    tgz_path = os.path.join(housing_path, "housing.tgz")
    urllib.request.urlretrieve(housing_url, tgz_path)
    housing_tgz = tarfile.open(tgz_path)
    housing_tgz.extractall(path=housing_path)
    housing_tgz.close()
fetch_housing_data()```


  [1]: 

您用来下载存档的URL似乎不​​正确;您正在下载 HTML 文件,因此出现错误。正确的 URL 应该是:https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.tgz - 注意域名。