From c38183033fe0169687abb4ae869d8dbcabea8f13 Mon Sep 17 00:00:00 2001 From: Alexis Simon Date: Fri, 16 Jan 2026 09:37:40 +0100 Subject: [PATCH] python/tskit/util.py: Add a file name to FileFormatError Closes #2467 Uses the .add_note method of exception, introduced in Python 3.11. Also hardcodes the file name in the raised from exceptions for HDF5 or zip. Until 3.10 is EOF, needs the sys module. --- python/tskit/util.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/python/tskit/util.py b/python/tskit/util.py index 64fad3f423..ab82861e33 100644 --- a/python/tskit/util.py +++ b/python/tskit/util.py @@ -31,6 +31,7 @@ import numbers import os import textwrap +import sys from typing import Union import numpy as np @@ -878,6 +879,10 @@ def raise_known_file_format_errors(open_file, existing_exception): Sniffs the file for pk-zip or hdf header bytes, then raises an exception if these are detected, if not raises the existing exception. """ + if (sys.version_info[0] >= 3) & (sys.version_info[1] > 10): + # add_note has been added in python 3.11 + # This condition can be removed once 3.10 is end-of-life + existing_exception.add_note(f"While trying to load {open_file.name}") # Check for HDF5 header bytes try: open_file.seek(0) @@ -887,14 +892,14 @@ def raise_known_file_format_errors(open_file, existing_exception): raise existing_exception if header == b"\x89HDF": raise tskit.FileFormatError( - "The specified file appears to be in HDF5 format. This file " + f"The file {open_file.name} appears to be in HDF5 format. This file " "may have been generated by msprime < 0.6.0 (June 2018) which " "can no longer be read directly. Please convert to the new " "kastore format using the ``tskit upgrade`` command from tskit version<0.6.2" ) from existing_exception if header[:2] == b"\x50\x4b": raise tskit.FileFormatError( - "The specified file appears to be in zip format, so may be a compressed " + f"The file {open_file.name} appears to be in zip format, so may be a compressed " "tree sequence. Try using the tszip module to decompress this file before " "loading. `pip install tszip; tsunzip ` or use " "`tszip.decompress` in Python code."