如何优雅地保存名为: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
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