Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 4 additions & 16 deletions 20 astropy/io/fits/hdu/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1338,12 +1338,9 @@ def _load_data(cls, fileobj, coldefs=None):
"""
Read the table data from the ASCII file output by BinTableHDU.dump().
"""
close_file = False

if isinstance(fileobj, path_like):
fileobj = os.path.expanduser(fileobj)
fileobj = open(fileobj)
close_file = True
with open(os.path.expanduser(fileobj)) as f:
return cls._load_data(f, coldefs=coldefs)

initialpos = fileobj.tell() # We'll be returning here later
linereader = csv.reader(fileobj, dialect=FITSTableDumpDialect)
Expand Down Expand Up @@ -1474,9 +1471,6 @@ def format_value(col, val):

col += 1

if close_file:
fileobj.close()

return data

@classmethod
Expand All @@ -1485,12 +1479,9 @@ def _load_coldefs(cls, fileobj):
Read the table column definitions from the ASCII file output by
BinTableHDU.dump().
"""
close_file = False

if isinstance(fileobj, path_like):
fileobj = os.path.expanduser(fileobj)
fileobj = open(fileobj)
close_file = True
with open(os.path.expanduser(fileobj)) as f:
return cls._load_coldefs(f)

columns = []

Expand All @@ -1507,9 +1498,6 @@ def _load_coldefs(cls, fileobj):
kwargs[key] = word
columns.append(Column(**kwargs))

if close_file:
fileobj.close()

return ColDefs(columns)


Expand Down
14 changes: 14 additions & 0 deletions 14 astropy/io/fits/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -4529,3 +4529,17 @@ def test_zero_row_string_column(tmp_path):
with fits.open(outfile) as hdul:
table_data = hdul[1].data
assert table_data.shape[0] == 0


def test_bintable_load_exception_closes_files(tmp_path):
datafile = tmp_path / "data.txt"
cdfile = tmp_path / "coldefs.txt"
datafile.write_text("1 2.0\n", encoding="utf-8")
cdfile.write_text("MALFORMED_LINE\n", encoding="utf-8")

with pytest.raises(IndexError):
fits.BinTableHDU.load(datafile=datafile, cdfile=cdfile)

# Verify files are closed and can be unlinked immediately (prevents WinError 32 on Windows)
cdfile.unlink()
datafile.unlink()
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.