Skip to content

Commit 3346689

Browse files
committed
Add fn to coerce pathlike to string
1 parent b44c06b commit 3346689

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

nibabel/loadsave.py

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import os
1313
import numpy as np
14+
import pathlib
1415

1516
from .filename_parser import splitext_addext
1617
from .openers import ImageOpener
@@ -19,6 +20,33 @@
1920
from .arrayproxy import is_proxy
2021
from .deprecated import deprecate_with_version
2122

23+
def _stringify_path(filepath_or_buffer):
24+
"""Attempt to convert a path-like object to a string.
25+
26+
Parameters
27+
----------
28+
filepath_or_buffer : object to be converted
29+
Returns
30+
-------
31+
str_filepath_or_buffer : maybe a string version of the object
32+
Notes
33+
-----
34+
Objects supporting the fspath protocol (python 3.6+) are coerced
35+
according to its __fspath__ method.
36+
For backwards compatibility with older pythons, pathlib.Path and
37+
py.path objects are specially coerced.
38+
Any other object is passed through unchanged, which includes bytes,
39+
strings, buffers, or anything else that's not even path-like.
40+
41+
Copied from:
42+
https://github.com/pandas-dev/pandas/blob/325dd686de1589c17731cf93b649ed5ccb5a99b4/pandas/io/common.py#L131-L160
43+
"""
44+
if hasattr(filepath_or_buffer, "__fspath__"):
45+
return filepath_or_buffer.__fspath__()
46+
elif isinstance(filepath_or_buffer, pathlib.Path):
47+
return str(filepath_or_buffer)
48+
return filepath_or_buffer
49+
2250

2351
def load(filename, **kwargs):
2452
''' Load file given filename, guessing at file type
@@ -35,11 +63,6 @@ def load(filename, **kwargs):
3563
img : ``SpatialImage``
3664
Image of guessed type
3765
'''
38-
#Coerce pathlib objects
39-
if hasattr(filename, '__fspath__'):
40-
filename = filename.__fspath__()
41-
else:
42-
filename = str(filename)
4366

4467
#Check file exists and is not empty
4568
try:

0 commit comments

Comments
 (0)