How to get the parent dir location

前端 未结 11 2005
鱼传尺愫
鱼传尺愫 2020-12-07 10:34

this code is get the templates/blog1/page.html in b.py:

path = os.path.join(os.path.dirname(__file__), os.path.join(\'templates\', \'blog1/page.html\'))
         


        
11条回答
  •  一个人的身影
    2020-12-07 11:15

    I think use this is better:

    os.path.realpath(__file__).rsplit('/', X)[0]
    
    
    In [1]: __file__ = "/aParent/templates/blog1/page.html"
    
    In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
    Out[3]: '/aParent'
    
    In [4]: __file__ = "/aParent/templates/blog1/page.html"
    
    In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
    Out[6]: '/aParent/templates/blog1'
    
    In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
    Out[8]: '/aParent/templates'
    
    In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
    Out[10]: '/aParent'
    

提交回复
热议问题