如何解决文件重命名添加后缀
如何从以下变量 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。