为了账号安全,请及时绑定邮箱和手机立即绑定

在 python 中构建路径

在 python 中构建路径

慕哥9229398 2023-02-22 16:45:02
'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'
查看完整描述

3 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

由于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实现你想要的。



查看完整回答
反对 回复 2023-02-22
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

pathlib可以使这更容易。它类似os.path但实现为适合方法链接的类。


from pathlib import Path


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


查看完整回答
反对 回复 2023-02-22
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

打印(os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(文件))),“模板”))



查看完整回答
反对 回复 2023-02-22
  • 3 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信