user11339173
user11339173

Reputation:

Don't understand how os.path.dirname() work

I'm pretty new to the Python world and would like to know if someone can explain this line of code?

I know it adds the directory of the target file to the sys.path, but don't know how it is going on.

sys.path.append(os.path.dirname(os.path.dirname(__file__)))

Upvotes: 1

Views: 8429

Answers (1)

Matias Cicero
Matias Cicero

Reputation: 26301

Let's start by explaining some things:

  • __file__ is a Python built-in. It yields the absolute path of the current executing script.

  • os.path.dirname returns the directory of a given path name, e.g. if given the input /a/b/c/d, it would yield /a/b/c.

  • sys.path is a list of directories that Python will use to search for modules when you try to import something.


os.path.dirname(__file__) returns the parent directory of the current script being executed (i.e. ../)

os.path.dirname(os.path.dirname(__file__)) returns the parent directory of the parent directory of the current script being executed. (i.e. ../../)

os.path.append(os.path.dirname(os.path.dirname(__file__))) will register the parent directory of the parent directory of the current executing script as a place to lookup new modules.


So, let's say we have the following directory structure:

a
|- b
|- c
|-----d
|     |----e
|     |    |---- f
|     |    |     |- main.py
|     |    |- bar.py
|     |- foo.py
|- foobar.py

Providing the script that contains this code is main.py, then the end result will be sys.path.append('/a/d/e'), so you'd be able to do import bar (but not import foo or import foobar)

Upvotes: 7

Related Questions