d2l-ai/d2l-zh · error · AssertionError

只有zip/tar文件可以被解压缩

Error message

只有zip/tar文件可以被解压缩

What it means

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.

Source

Thrown at d2l/torch.py:406

    print(f'正在从{url}下载{fname}...')
    r = requests.get(url, stream=True, verify=True)
    with open(fname, 'wb') as f:
        f.write(r.content)
    return fname

def download_extract(name, folder=None):
    """下载并解压zip/tar文件

    Defined in :numref:`sec_kaggle_house`"""
    fname = download(name)
    base_dir = os.path.dirname(fname)
    data_dir, ext = os.path.splitext(fname)
    if ext == '.zip':
        fp = zipfile.ZipFile(fname, 'r')
    elif ext in ('.tar', '.gz'):
        fp = tarfile.open(fname, 'r')
    else:
        assert False, '只有zip/tar文件可以被解压缩'
    fp.extractall(base_dir)
    return os.path.join(base_dir, folder) if folder else data_dir

def download_all():
    """下载DATA_HUB中的所有文件

    Defined in :numref:`sec_kaggle_house`"""
    for name in DATA_HUB:
        download(name)

DATA_HUB['kaggle_house_train'] = (
    DATA_URL + 'kaggle_house_pred_train.csv',
    '585e9cc93e70b39160e7921475f9bcd7d31219ce')

DATA_HUB['kaggle_house_test'] = (
    DATA_URL + 'kaggle_house_pred_test.csv',
    'fa19780a7b011d9b009e8bff8e99922a8ee2eb90')

View on GitHub (pinned to e6b18ccea7)

Solutions

  1. Repackage or re-link the data as .zip or .tar/.gz and update the DATA_HUB URL
  2. For already-uncompressed files, call d2l.download(name) and read the file directly (pd.read_csv on the returned fname)
  3. Rename a mislabeled file after verifying its true type with `file <fname>`
  4. Locally relax the whitelist: `elif ext in ('.tar', '.gz', '.tgz', '.bz2'):` and open with tarfile.open(fname, 'r:*')

Example fix

# before
DATA_HUB['mydata'] = (DATA_URL + 'mydata.csv', sha1)
d2l.download_extract('mydata')  # AssertionError: 只有zip/tar文件可以被解压缩
# after
fname = d2l.download('mydata')          # plain download works for csv
df = pd.read_csv(fname)
# or point at an archive
DATA_HUB['mydata'] = (DATA_URL + 'mydata.tar.gz', sha1_tar)
d2l.download_extract('mydata')
Defensive patterns

Strategy: validation

Validate before calling

import os
fname = d2l.DATA_HUB[name][0].split('/')[-1]
ext = os.path.splitext(fname)[1]
if ext not in ('.zip', '.tar', '.gz'):
    raise ValueError(f'cannot extract {ext}; use download() for plain files')
path = d2l.download_extract(name)

Type guard

def is_extractable(name: str, hub=d2l.DATA_HUB) -> bool:
    return os.path.splitext(hub[name][0].split('/')[-1])[1] in ('.zip', '.tar', '.gz')

Prevention

When it happens

Trigger: 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.

Common situations: 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'.

Related errors


AI-assisted analysis of d2l-ai/d2l-zh@e6b18ccea7 (2026-08-14). Data as JSON: /api/errors/738a4d22d043d586. Report an issue: GitHub.