Skip to content

Commit a974b70

Browse files
committed
better file checks - path.exists is try/except for os.stat anyways!
1 parent d207360 commit a974b70

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

nibabel/loadsave.py

Lines changed: 6 additions & 4 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,9 +36,11 @@ 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)
41-
if op.getsize(filename) <= 0:
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:
4244
raise ImageFileError("Empty file: '%s'" % filename)
4345
sniff = None
4446
for image_klass in all_image_classes:

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)