Jupyter Notebook中from six.moves导入模块触发ImportError如何修复
报错修复方法
- 核心错误原因是拼写问题:你导入时写的
usrllib拼写错误,正确库名是urllib,把第三行代码替换为from six.moves import urllib即可解决当前ImportError报错。 - 你代码中
create housing_url ,housing_path属于无效语法,没有对应的Python语法支持,直接删除这一行即可,否则后续执行还会触发语法错误。
修复后完整可运行代码
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") 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") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close()
可选优化方案
如果你使用的是Python3环境,不需要兼容Python2的话,可以直接去掉six库的依赖,把导入语句替换为import urllib.request,调用逻辑不需要调整,适配性更好。
内容的提问来源于stack exchange,提问作者jane
相关产品推荐
相关产品推荐

