Skip to content

Commit b53a452

Browse files
Merge pull request #611 from raamana/empty_files
MRG: detect empty file and raise specific error
2 parents ee1a5fc + a974b70 commit b53a452

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

nibabel/loadsave.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
# module imports
1010
""" Utilities to load and save image objects """
1111

12-
import os.path as op
12+
import os
1313
import numpy as np
1414

1515
from .filename_parser import splitext_addext
@@ -36,8 +36,12 @@ def load(filename, **kwargs):
3636
img : ``SpatialImage``
3737
Image of guessed type
3838
'''
39-
if not op.exists(filename):
40-
raise FileNotFoundError("No such file: '%s'" % filename)
39+
try:
40+
stat_result = os.stat(filename)
41+
except OSError:
42+
raise FileNotFoundError("No such file or no access: '%s'" % filename)
43+
if stat_result.st_size <= 0:
44+
raise ImageFileError("Empty file: '%s'" % filename)
4145
sniff = None
4246
for image_klass in all_image_classes:
4347
is_valid, sniff = image_klass.path_maybe_image(filename, sniff)

nibabel/tests/test_loadsave.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ def test_file_not_found():
5858
assert_raises(FileNotFoundError, load, 'does_not_exist.nii.gz')
5959

6060

61+
def test_load_empty_image():
62+
with InTemporaryDirectory():
63+
open('empty.nii', 'w').close()
64+
with assert_raises(ImageFileError) as err:
65+
load('empty.nii')
66+
assert_true(err.exception.args[0].startswith('Empty file: '))
67+
68+
6169
def test_read_img_data_nifti():
6270
shape = (2, 3, 4)
6371
data = np.random.normal(size=shape)

0 commit comments

Comments
 (0)