使用扩展名保存时命名文件

问题描述 投票:0回答:1

如何优雅地保存名为:oldname+"_new"+扩展名的文件?

我目前做的是:

ext = os.path.splitext(file)[1]
output_file = (root+'/'+ os.path.splitext(file)[0]+"_new"+ext)
#or output_file = (os.path.join(root, os.path.splitext(file)[0])+'_new'+ext)

with open(output_file, 'w', encoding='utf-8') as file:
      file.write(text)

(借助 Python:如何在使用操作系统重命名文件时保留文件扩展名?,但不重复)

-- 我使用Python 3.12.2

python file os.path code-readability
1个回答
0
投票

pathlib.Path 在现代代码中是更面向对象的方法的首选。

例如:

from pathlib import Path

def makenew(filename: Path, new: str = "_new") -> Path:
    return Path(filename.parent / (filename.stem + new + filename.suffix))

print(makenew(Path("/Users/SIGHUP/foo.txt")))

输出:

/Users/SIGHUP/foo_new.txt
© www.soinside.com 2019 - 2024. All rights reserved.