Skip to content

Commit f1f9901

Browse files
Allow relative and home paths
1 parent 4e7ad07 commit f1f9901

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

nibabel/filename_parser.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from __future__ import annotations
1111

1212
import os
13+
import pathlib
1314
import typing as ty
1415

1516
if ty.TYPE_CHECKING: # pragma: no cover
@@ -37,9 +38,7 @@ def _stringify_path(filepath_or_buffer: FileSpec) -> str:
3738
Adapted from:
3839
https://github.com/pandas-dev/pandas/blob/325dd68/pandas/io/common.py#L131-L160
3940
"""
40-
if isinstance(filepath_or_buffer, os.PathLike):
41-
return filepath_or_buffer.__fspath__()
42-
return filepath_or_buffer
41+
return str(pathlib.Path(filepath_or_buffer).expanduser().resolve())
4342

4443

4544
def types_filenames(

nibabel/tests/test_filename_parser.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
#
88
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
99
"""Tests for filename container"""
10+
import pathlib
1011

1112
import pytest
1213

13-
from ..filename_parser import TypesFilenamesError, parse_filename, splitext_addext, types_filenames
14+
from ..filename_parser import TypesFilenamesError, parse_filename, splitext_addext, types_filenames, _stringify_path
1415

1516

1617
def test_filenames():
@@ -123,3 +124,26 @@ def test_splitext_addext():
123124
assert res == ('..', '', '')
124125
res = splitext_addext('...')
125126
assert res == ('...', '', '')
127+
128+
129+
def test__stringify_path():
130+
current_directory = pathlib.Path.cwd()
131+
res = _stringify_path('')
132+
assert res == str(current_directory)
133+
res = _stringify_path('fname.ext.gz')
134+
assert res == str(current_directory / 'fname.ext.gz')
135+
res = _stringify_path(pathlib.Path('fname.ext.gz'))
136+
assert res == str(current_directory / 'fname.ext.gz')
137+
138+
home = pathlib.Path.home()
139+
res = _stringify_path(pathlib.Path('~/fname.ext.gz'))
140+
assert res == str(home) + '/fname.ext.gz'
141+
142+
res = _stringify_path(pathlib.Path('./fname.ext.gz'))
143+
assert res == str(current_directory / 'fname.ext.gz')
144+
res = _stringify_path(pathlib.Path('../fname.ext.gz'))
145+
assert res == str(current_directory.parent / 'fname.ext.gz')
146+
147+
148+
149+

0 commit comments

Comments
 (0)