pathlib可以使这更容易。它类似os.path但实现为适合方法链接的类。from pathlib import Pathfilename = "would be nice if OP gave us the test input"templates = Path(filename).absolute().parents[2].joinpath('templates')templates仍然是一个Path对象。一些 API 接受Path,但您也可以templates = str(templates)获取路径字符串。