【发布时间】:2021-03-25 13:58:24
【问题描述】:
如何从以下变量中添加 fIN = T1_r.nii.gz
以下后缀_brain 并创建以下输出文件名?
fOut = T1_r_brain.nii.gz
当我使用以下命令行时
fIn2, file_extension = os.path.splitext(fIn)
它只会删除 .gz 扩展名。 谢谢您的帮助 弗雷德
【问题讨论】:
如何从以下变量中添加 fIN = T1_r.nii.gz
以下后缀_brain 并创建以下输出文件名?
fOut = T1_r_brain.nii.gz
当我使用以下命令行时
fIn2, file_extension = os.path.splitext(fIn)
它只会删除 .gz 扩展名。 谢谢您的帮助 弗雷德
【问题讨论】:
我必须为此编写一个实用程序,这就是我想出的。
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)
这是一个例子:
>>> f_in = "T1_r.nii.gz"
>>> add_str_before_suffixes(f_in, "_brain")
PosixPath('T1_r_brain.nii.gz')
【讨论】:
split_path = 'T1_r.nii.gz'.split('.')
split_path[0] += '_brain'
final_path = ".".join(split_path)
【讨论】: