os.getcwd() vs os.path.abspath(os.path.dirname(__file__)) [duplicate]

As mouad said, os.getcwd() won’t give you exactly what you’re expecting.

os.getcwd() does a bit more than returning the current working directory. It defaults to $PWD in your env. It’s not where the script is located but where you were when you executed the script.

Being in /home/user and doing python manage.py, os.getcwd() will return /home/user
Being in /home/ and doing python user/manage.py, os.getcwd() will return /home

But it’s still won’t be always true since it’s possible to use os.chdir(). It is in other word like doing cd. It will also change the return value of os.getcwd().

On the other hand. __file__ is the path of the module file. So you have to use this to be certain to have a path relative to your module instead of the current working directory that may change.

As ShawnFumo said, __file__ might not be always absolute. To get a better idea on how it works, you can check that answer: Python __file__ attribute. Also, as of Python3.4 __file__ should always be an absolute path.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)