How to get the parent dir location

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

    Here is another relatively simple solution that:

    • does not use dirname() (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
    • does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

    it just uses normpath and join:

    def parent(p):
        return os.path.normpath(os.path.join(p, os.path.pardir))
    
    # Example:
    for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
            'dir/file.txt', '../up/', '/abs/path']:
        print parent(p)
    

    Result:

    .
    foo/bar
    with/trailing
    dir
    ..
    /abs
    

提交回复
热议问题