Search code examples
pythondirectoryparent

python parent directory


I want to get the parent directory of a file. This code doesn't work:

projectRoot = os.path.dirname(os.pardir(os.path.abspath(__file__)))

What's wrong?

(I am developing a django application, and use this variable in the settings file of my application)

Thanks.

Romain


Solution

  • You can access the parent directory by using ..

    import os
    os.path.join(os.path.dirname(__file__), os.pardir)
    

    OR:

    import os
    split_limit = 1 if os.path.isdir(__file__) else 0
    parent_dir = os.path.abspath(__file__).rsplit(os.path.sep, split_limit)[0]