Skip to content

Commit 312bc4d

Browse files
committed
Merge pull request #455 from arokem/file-not-found
MRG: FileNotFound error for file not found Currently, when a file doesn't exist (for example, if you typo'd the file-name), you get a relatively cryptic error: "couldn't work out file-type for file foo.nii.gz". Here we check if the file exists first, and raise an informative error up front if it doesn't exist.
2 parents 791b10f + 26d003b commit 312bc4d

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

nibabel/loadsave.py

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

12+
import os.path as op
1213
import numpy as np
1314
import warnings
1415

@@ -17,6 +18,7 @@
1718
from .filebasedimages import ImageFileError
1819
from .imageclasses import all_image_classes
1920
from .arrayproxy import is_proxy
21+
from .py3k import FileNotFoundError
2022

2123

2224
def load(filename, **kwargs):
@@ -34,6 +36,8 @@ def load(filename, **kwargs):
3436
img : ``SpatialImage``
3537
Image of guessed type
3638
'''
39+
if not op.exists(filename):
40+
raise FileNotFoundError("No such file: '%s'" % filename)
3741
sniff = None
3842
for image_klass in all_image_classes:
3943
is_valid, sniff = image_klass.path_maybe_image(filename, sniff)

nibabel/py3k.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def open_latin1(filename, mode='r'):
4040
strchar = 'U'
4141
ints2bytes = lambda seq: bytes(seq)
4242
ZEROB = bytes([0])
43+
FileNotFoundError = FileNotFoundError
4344
else:
4445
import StringIO
4546
StringIO = BytesIO = StringIO.StringIO
@@ -63,6 +64,9 @@ def open_latin1(filename, mode='r'):
6364
ZEROB = chr(0)
6465

6566

67+
class FileNotFoundError(IOError):
68+
pass
69+
6670
def getexception():
6771
return sys.exc_info()[1]
6872

nibabel/tests/test_loadsave.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from nose.tools import (assert_true, assert_false, assert_raises,
2424
assert_equal, assert_not_equal)
25+
from ..py3k import FileNotFoundError
2526

2627
data_path = pjoin(dirname(__file__), 'data')
2728

@@ -53,6 +54,10 @@ def test_read_img_data():
5354
del img
5455

5556

57+
def test_file_not_found():
58+
assert_raises(FileNotFoundError, load, 'does_not_exist.nii.gz')
59+
60+
5661
def test_read_img_data_nifti():
5762
shape = (2, 3, 4)
5863
data = np.random.normal(size=shape)

0 commit comments

Comments
 (0)