Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Accept pathlib.Path objects where filenames are accepted #610

Merged
merged 18 commits into from
Oct 23, 2019
Merged
Show file tree
Hide file tree
Changes from 7 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
5 changes: 4 additions & 1 deletion nibabel/filebasedimages.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from copy import deepcopy
from .fileholders import FileHolder
from .filename_parser import (types_filenames, TypesFilenamesError,
splitext_addext)
splitext_addext, _stringify_path)
effigies marked this conversation as resolved.
Show resolved Hide resolved
from .openers import ImageOpener
from .deprecated import deprecate_with_version

Expand Down Expand Up @@ -252,10 +252,12 @@ def set_filename(self, filename):
``.file_map`` attribute. Otherwise, the image instance will
try and guess the other filenames from this given filename.
'''
filename = _stringify_path(filename)
effigies marked this conversation as resolved.
Show resolved Hide resolved
self.file_map = self.__class__.filespec_to_file_map(filename)

@classmethod
def from_filename(klass, filename):
filename = _stringify_path(filename)
file_map = klass.filespec_to_file_map(filename)
return klass.from_file_map(file_map)

Expand Down Expand Up @@ -330,6 +332,7 @@ def to_filename(self, filename):
-------
None
'''
filename = _stringify_path(filename)
self.file_map = self.filespec_to_file_map(filename)
self.to_file_map()

Expand Down
34 changes: 34 additions & 0 deletions nibabel/filename_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,41 @@
except NameError:
basestring = str
effigies marked this conversation as resolved.
Show resolved Hide resolved

import pathlib


class TypesFilenamesError(Exception):
pass


def _stringify_path(filepath_or_buffer):
"""Attempt to convert a path-like object to a string.

Parameters
----------
filepath_or_buffer : object to be converted
effigies marked this conversation as resolved.
Show resolved Hide resolved
Returns
-------
str_filepath_or_buffer : maybe a string version of the object
effigies marked this conversation as resolved.
Show resolved Hide resolved
Notes
-----
Objects supporting the fspath protocol (python 3.6+) are coerced
according to its __fspath__ method.
For backwards compatibility with older pythons, pathlib.Path and
py.path objects are specially coerced.
effigies marked this conversation as resolved.
Show resolved Hide resolved
Any other object is passed through unchanged, which includes bytes,
strings, buffers, or anything else that's not even path-like.

Copied from:
https://github.com/pandas-dev/pandas/blob/325dd686de1589c17731cf93b649ed5ccb5a99b4/pandas/io/common.py#L131-L160
"""
if hasattr(filepath_or_buffer, "__fspath__"):
return filepath_or_buffer.__fspath__()
elif isinstance(filepath_or_buffer, pathlib.Path):
return str(filepath_or_buffer)
return filepath_or_buffer


def types_filenames(template_fname, types_exts,
effigies marked this conversation as resolved.
Show resolved Hide resolved
trailing_suffixes=('.gz', '.bz2'),
enforce_extensions=True,
Expand Down Expand Up @@ -190,6 +220,8 @@ def parse_filename(filename,
>>> parse_filename('/path/fnameext2.gz', types_exts, ('.gz',))
('/path/fname', 'ext2', '.gz', 't2')
'''
filename = _stringify_path(filename)

ignored = None
if match_case:
endswith = _endswith
Expand Down Expand Up @@ -257,6 +289,8 @@ def splitext_addext(filename,
>>> splitext_addext('fname.ext.foo', ('.foo', '.bar'))
('fname', '.ext', '.foo')
'''
filename = _stringify_path(filename)

if match_case:
endswith = _endswith
else:
Expand Down
7 changes: 6 additions & 1 deletion nibabel/loadsave.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import os
import numpy as np

from .filename_parser import splitext_addext
from .filename_parser import splitext_addext, _stringify_path
from .openers import ImageOpener
from .filebasedimages import ImageFileError
from .imageclasses import all_image_classes
Expand All @@ -35,12 +35,16 @@ def load(filename, **kwargs):
img : ``SpatialImage``
Image of guessed type
'''
filename = _stringify_path(filename)
effigies marked this conversation as resolved.
Show resolved Hide resolved

# Check file exists and is not empty
try:
stat_result = os.stat(filename)
except OSError:
raise FileNotFoundError("No such file or no access: '%s'" % filename)
if stat_result.st_size <= 0:
raise ImageFileError("Empty file: '%s'" % filename)

sniff = None
for image_klass in all_image_classes:
is_valid, sniff = image_klass.path_maybe_image(filename, sniff)
Expand Down Expand Up @@ -92,6 +96,7 @@ def save(img, filename):
-------
None
'''
filename = _stringify_path(filename)
effigies marked this conversation as resolved.
Show resolved Hide resolved

# Save the type as expected
try:
Expand Down