1

How could I add from the following variable fIN = T1_r.nii.gz the following suffix _brain and create the following output filename?

fOut = T1_r_brain.nii.gz

When I use the following command line

fIn2, file_extension = os.path.splitext(fIn)

it only removes the .gz extension. Thank you for your help Fred

buran
  • 13,682
  • 10
  • 36
  • 61
fredooms
  • 123
  • 8
  • 1
    Does this answer your question? [Clean way to get the "true" stem of a Path object?](https://stackoverflow.com/questions/31890341/clean-way-to-get-the-true-stem-of-a-path-object) – iacob Mar 25 '21 at 14:08

2 Answers2

1

I had to write a utility for this, and here's what I came up with.

from pathlib import Path

def add_str_before_suffixes(filepath, string: str) -> Path:
    """Append a string to a filename immediately before extension(s).
    
    Parameters
    ----------
    filepath : Path-like
        Path to modify. Can contain multiple extensions like `.bed.gz`.
    string : str
        String to append to filename.
    
    Returns
    -------
    Instance of `pathlib.Path`.
    
    Examples
    --------
    >>> add_str_before_suffixes("foo", "_baz")
    PosixPath('foo_baz')
    >>> add_str_before_suffixes("foo.bed", "_baz")
    PosixPath('foo_baz.bed')
    >>> add_str_before_suffixes("foo.bed.gz", "_baz")
    PosixPath('foo_baz.bed.gz')
    """
    filepath = Path(filepath)
    suffix = "".join(filepath.suffixes)
    orig_name = filepath.name.replace(suffix, "")
    new_name = f"{orig_name}{string}{suffix}"
    return filepath.with_name(new_name)

Here is an example:

>>> f_in = "T1_r.nii.gz"
>>> add_str_before_suffixes(f_in, "_brain")
PosixPath('T1_r_brain.nii.gz')
jkr
  • 17,119
  • 2
  • 42
  • 68
  • This is a good solution. But does it have to be this complicated? – revmatcher Mar 25 '21 at 14:27
  • Good point. I like your solution. I was adamant about using pathlib functions. – jkr Mar 25 '21 at 14:44
  • Well, we could propose this as a feature addition to the Pathlib package. Although, I'm unsure as to how to accomplish that and as to whether the community in general would find that beneficial. Your thoughts? – revmatcher Mar 26 '21 at 04:33
  • I personally don't think this would be a useful feature addition to pathlib. What I meant by my previous comment is that my judgment was clouded by my desire to use pathlib. – jkr Mar 26 '21 at 13:25
1
split_path = 'T1_r.nii.gz'.split('.')
    
split_path[0] += '_brain'
    
final_path = ".".join(split_path)
revmatcher
  • 757
  • 8
  • 17