How to get the parent dir location

前端 未结 11 2003
鱼传尺愫
鱼传尺愫 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:16

    os.path.abspath doesn't validate anything, so if we're already appending strings to __file__ there's no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

    # climb to __file__'s parent's parent:
    os.path.abspath(__file__ + "/../../")
    

    That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

    But, since we know how many levels to climb, we could clean this up with a simple little function:

    uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
    
    # __file__ = "/aParent/templates/blog1/page.html"
    >>> uppath(__file__, 1)
    '/aParent/templates/blog1'
    >>> uppath(__file__, 2)
    '/aParent/templates'
    >>> uppath(__file__, 3)
    '/aParent'
    

提交回复
热议问题