python: get directory two levels up

后端 未结 12 1928
清歌不尽
清歌不尽 2021-01-30 06:00

Ok...I dont know where module x is, but I know that I need to get the path to the directory two levels up.

So, is there a more elegant way to do:

         


        
相关标签:
12条回答
  • 2021-01-30 06:33

    You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.

    from pathlib import Path
    
    p = Path(__file__).parents[1]
    
    print(p)
    # /absolute/path/to/two/levels/up
    

    This uses the parents sequence which provides access to the parent directories and chooses the 2nd one up.

    Note that p in this case will be some form of Path object, with their own methods. If you need the paths as string then you can call str on them.

    0 讨论(0)
  • 2021-01-30 06:33

    Assuming you want to access folder named xzy two folders up your python file. This works for me and platform independent.

    ".././xyz"

    0 讨论(0)
  • 2021-01-30 06:34

    Very easy:

    Here is what you want:

    import os.path as path
    
    two_up =  path.abspath(path.join(__file__ ,"../.."))
    
    0 讨论(0)
  • 2021-01-30 06:35

    For getting the directory 2 levels up:

     import os.path as path
     two_up = path.abspath(path.join(os.getcwd(),"../.."))
    
    0 讨论(0)
  • 2021-01-30 06:38

    (pathlib.Path('../../') ).resolve()

    0 讨论(0)
  • 2021-01-30 06:39

    I have found that the following works well in 2.7.x

    import os
    two_up = os.path.normpath(os.path.join(__file__,'../'))
    
    0 讨论(0)
提交回复
热议问题