python: get directory two levels up

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

    I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.

    import os
    
    grandparent_dir = os.path.abspath(  # Convert into absolute path string
        os.path.join(  # Current file's grandparent directory
            os.path.join(  # Current file's parent directory
                os.path.dirname(  # Current file's directory
                    os.path.abspath(__file__)  # Current file path
                ),
                os.pardir
            ),
            os.pardir
        )
    )
    
    print grandparent_dir
    

    And to prove it works, here I start out in ~/Documents/notes just so that I show the current directory doesn't influence outcome. I put the file grandpa.py with that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.

    (testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py 
    /Users/alancoding/Documents/scripts/grandpa.py
    (testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py 
    /Users/alancoding
    

    This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.

提交回复
热议问题