How to get the parent dir location

前端 未结 11 1972
鱼传尺愫
鱼传尺愫 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
    
    0 讨论(0)
  • 2020-12-07 11:22

    Use relative path with the pathlib module in Python 3.4+:

    from pathlib import Path
    
    Path(__file__).parent
    

    You can use multiple calls to parent to go further in the path:

    Path(__file__).parent.parent
    

    As an alternative to specifying parent twice, you can use:

    Path(__file__).parents[1]
    
    0 讨论(0)
  • 2020-12-07 11:29
    os.path.dirname(os.path.abspath(__file__))
    

    Should give you the path to a.

    But if b.py is the file that is currently executed, then you can achieve the same by just doing

    os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
    
    0 讨论(0)
  • 2020-12-07 11:32

    You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).

    0 讨论(0)
  • 2020-12-07 11:33

    May be join two .. folder, to get parent of the parent folder?

    path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
    
    0 讨论(0)
提交回复
热议问题