python: get directory two levels up

后端 未结 12 1961
清歌不尽
清歌不尽 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:42

    More cross-platform implementation will be:

    import pathlib
    two_up = (pathlib.Path(__file__) / ".." / "..").resolve()
    

    Using parent is not supported on Windows. Also need to add .resolve(), to:

    Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)

提交回复
热议问题