d2l-ai/d2l-zh · error · AssertionError

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

Error message

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

What it means

An AssertionError (assert False) in d2l.paddle.download_extract raised when the downloaded file's extension is not .zip, .tar, or .gz. The helper can only extract archives via zipfile.ZipFile or tarfile.open; the Chinese message translates to 'only zip/tar files can be extracted'.

Source

Thrown at d2l/paddle.py:417

    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. Use d2l.download(name) for non-archive files — extraction is not needed.
  2. Register/point to .zip or .tar.gz mirrors when you truly need extraction.
  3. Handle .bz2/.xz yourself with tarfile.open(fname, 'r:bz2'|'r:xz') in custom code.
  4. Verify the extension logic: os.path.splitext('a.tar.gz') returns '.gz' (handled), but 'a.csv' returns '.csv' (rejected).

Example fix

# before
d2l.DATA_HUB['house'] = (d2l.DATA_URL + 'kaggle_house_pred_train.csv', sha1)
d2l.download_extract('house')  # AssertionError: csv not extractable
# after
d2l.download('house')  # returns path to the csv directly
Defensive patterns

Strategy: validation

Validate before calling

_, ext = os.path.splitext(fname)
if ext in ('.zip', '.tar', '.gz'):
    out = d2l.download_extract(name)
else:
    out = d2l.download(name)  # plain file needs no extraction

Type guard

def is_extractable(fname: str) -> bool:
    return os.path.splitext(fname)[1] in ('.zip', '.tar', '.gz')

Try / catch

try:
    d2l.download_extract(name)
except AssertionError as e:
    if 'zip/tar' in str(e):
        path = d2l.download(name)
    else:
        raise

Prevention

When it happens

Trigger: Calling download_extract on a DATA_HUB entry whose URL ends in .csv/.json/.txt; extensionless or query-string URLs; .bz2/.xz archives where os.path.splitext yields an unrecognized extension.

Common situations: Registering raw CSVs (the Kaggle house files) and mistakenly using download_extract instead of download; pointing DATA_HUB at third-party archives in formats the helper does not handle.

Related errors


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