在 python 中构建路径

'DIRS': [os.path.join(
      os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')],

决议:

'/opt/python/current/app/src/myproject/templates'

我需要对可能的代码进行哪些更改才能使 DIRS 解析为以下内容?

'/opt/python/current/app/src/templates'


慕哥9229398
浏览 97回答 3
3回答

白衣染霜花

由于os.path.dirname获取指定文件的目录名称(在您的例子中,您可以在此处__file__了解这意味着什么),您将获取该文件的父目录。现在os.path.abspath用文件名获取当前工作目录的绝对路径。最后os.path.join通过加入两条路径来工作。例如,如果您位于/opt/python/current/app/src/myproject/并且想要将templates文件夹加入该路径,您可以执行 os.path.join( /opt/python/current/app/src/myproject/, templates)所以为了得到你需要的东西,你需要做才能得到你需要的'DIRS' : [os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),'templates')],os.path.abspath获取的绝对规范化路径,__file__然后它获取第一个(最内层)的父目录os.path.dirname,第二个获取该结果路径父目录,依此类推。如果通过使用两个os.path.dirname你得到/opt/python/current/app/src/myproject/templates这意味着你还需要一个来os.path.dirname实现你想要的。

一只萌萌小番薯

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)获取路径字符串。

蛊毒传说

打印(os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(文件))),“模板”))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python