Skip to content
Merged
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
14 changes: 9 additions & 5 deletions nrrd/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,15 +387,17 @@ def read_data(header: NRRDHeader, fh: Optional[IO] = None, filename: Optional[st
else:
# Must close the file because if the file was opened above from detached filename, there is no "with" block to
# close it for us
fh.close()
if data_filename is not None:
fh.close()

raise NRRDError('Invalid lineskip, allowed values are greater than or equal to 0')

# Skip the requested number of bytes or seek backward, and then parse the data using NumPy
if byte_skip < -1:
# Must close the file because if the file was opened above from detached filename, there is no "with" block to
# close it for us
fh.close()
if data_filename is not None:
fh.close()

raise NRRDError('Invalid byteskip, allowed values are greater than or equal to -1')
elif byte_skip >= 0:
Expand Down Expand Up @@ -428,7 +430,8 @@ def read_data(header: NRRDHeader, fh: Optional[IO] = None, filename: Optional[st
else:
# Must close the file because if the file was opened above from detached filename, there is no "with" block
# to close it for us
fh.close()
if data_filename is not None:
fh.close()

raise NRRDError(f'Unsupported encoding: {header["encoding"]}')

Expand Down Expand Up @@ -461,8 +464,9 @@ def read_data(header: NRRDHeader, fh: Optional[IO] = None, filename: Optional[st
# NumPy
data = np.frombuffer(decompressed_data[byte_skip:], dtype)

# Close the file, even if opened using "with" block, closing it manually does not hurt
fh.close()
# Close the file if we opened it
if data_filename is not None:
fh.close()

if total_data_points != data.size:
raise NRRDError(f'Size of the data does not equal the product of all the dimensions: '
Expand Down
6 changes: 6 additions & 0 deletions nrrd/tests/test_reading.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,12 @@ def test_read_space_directions_list(self):
finally:
nrrd.SPACE_DIRECTIONS_TYPE = 'double matrix'

def test_file_parameter_not_closed(self):
with open(RAW_NRRD_FILE_PATH, 'rb') as fh:
header = nrrd.read_header(fh)
nrrd.read_data(header, fh)
self.assertFalse(fh.closed)


class TestReadingFunctionsFortran(Abstract.TestReadingFunctions):
index_order = 'F'
Expand Down