{"record":{"id":"738a4d22d043d586","repo":"d2l-ai/d2l-zh","slug":"zip-tar-738a4d","errorCode":null,"errorMessage":"只有zip/tar文件可以被解压缩","messagePattern":"只有zip/tar文件可以被解压缩","errorType":"validation","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"d2l/torch.py","lineNumber":406,"sourceCode":"    print(f'正在从{url}下载{fname}...')\n    r = requests.get(url, stream=True, verify=True)\n    with open(fname, 'wb') as f:\n        f.write(r.content)\n    return fname\n\ndef download_extract(name, folder=None):\n    \"\"\"下载并解压zip/tar文件\n\n    Defined in :numref:`sec_kaggle_house`\"\"\"\n    fname = download(name)\n    base_dir = os.path.dirname(fname)\n    data_dir, ext = os.path.splitext(fname)\n    if ext == '.zip':\n        fp = zipfile.ZipFile(fname, 'r')\n    elif ext in ('.tar', '.gz'):\n        fp = tarfile.open(fname, 'r')\n    else:\n        assert False, '只有zip/tar文件可以被解压缩'\n    fp.extractall(base_dir)\n    return os.path.join(base_dir, folder) if folder else data_dir\n\ndef download_all():\n    \"\"\"下载DATA_HUB中的所有文件\n\n    Defined in :numref:`sec_kaggle_house`\"\"\"\n    for name in DATA_HUB:\n        download(name)\n\nDATA_HUB['kaggle_house_train'] = (\n    DATA_URL + 'kaggle_house_pred_train.csv',\n    '585e9cc93e70b39160e7921475f9bcd7d31219ce')\n\nDATA_HUB['kaggle_house_test'] = (\n    DATA_URL + 'kaggle_house_pred_test.csv',\n    'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')\n","sourceCodeStart":388,"sourceCodeEnd":424,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/torch.py#L388-L424","documentation":"AssertionError from d2l.torch.download_extract: after os.path.splitext on the downloaded filename, only '.zip' (via zipfile.ZipFile) and '.tar'/'.gz' (via tarfile.open) are supported; any other extension trips assert False with the Chinese message 'only zip/tar files can be extracted'. It is a format whitelist for the extraction helper used in the Kaggle-house section.","triggerScenarios":"A DATA_HUB entry whose URL ends in '.csv', '.json', '.txt', '.rar', '.7z', or '.tgz' passed to download_extract; an archive whose extension was stripped or mistyped so splitext yields an unexpected ext.","commonSituations":"Users adapt the kaggle-house boilerplate to their own non-archived dataset; a mirror URL that appends query strings or different extensions; .tgz files even though tarfile could handle them, because the elif only matches '.tar' and '.gz'.","solutions":["Repackage or re-link the data as .zip or .tar/.gz and update the DATA_HUB URL","For already-uncompressed files, call d2l.download(name) and read the file directly (pd.read_csv on the returned fname)","Rename a mislabeled file after verifying its true type with `file <fname>`","Locally relax the whitelist: `elif ext in ('.tar', '.gz', '.tgz', '.bz2'):` and open with tarfile.open(fname, 'r:*')"],"exampleFix":"# before\nDATA_HUB['mydata'] = (DATA_URL + 'mydata.csv', sha1)\nd2l.download_extract('mydata')  # AssertionError: 只有zip/tar文件可以被解压缩\n# after\nfname = d2l.download('mydata')          # plain download works for csv\ndf = pd.read_csv(fname)\n# or point at an archive\nDATA_HUB['mydata'] = (DATA_URL + 'mydata.tar.gz', sha1_tar)\nd2l.download_extract('mydata')","handlingStrategy":"validation","validationCode":"import os\nfname = d2l.DATA_HUB[name][0].split('/')[-1]\next = os.path.splitext(fname)[1]\nif ext not in ('.zip', '.tar', '.gz'):\n    raise ValueError(f'cannot extract {ext}; use download() for plain files')\npath = d2l.download_extract(name)","typeGuard":"def is_extractable(name: str, hub=d2l.DATA_HUB) -> bool:\n    return os.path.splitext(hub[name][0].split('/')[-1])[1] in ('.zip', '.tar', '.gz')","tryCatchPattern":null,"preventionTips":["Check the extension embedded in the DATA_HUB URL before calling download_extract","Use plain download() + pd.read_csv for csv/json data","Package custom datasets as zip or tar.gz","Remember .tgz is NOT accepted by the built-in whitelist"],"tags":["d2l","pytorch","assertion","archive","zip","tar","download"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}