Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: get directory two levels up

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:

import os two_up = os.path.dirname(os.path.dirname(__file__)) 

Solutions for both Python 2 and 3 are welcome!

like image 642
jramm Avatar asked Jan 08 '15 15:01

jramm


People also ask

What does __ file __ mean in Python?

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

How do I see the parent directory in Python?

Get the Parent Directory in Python Using the dirname() Method of the os Module. The dirname() method of the os module takes path string as input and returns the parent directory as output.

What is os Pardir in Python?

Python os.pardir() has the following syntax: Copy os.pardir. The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX.


1 Answers

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.

like image 83
Ffisegydd Avatar answered Sep 27 '22 18:09

Ffisegydd