57👍
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.
12👍
The command os.path.abspath(os.path.dirname(__file__))
returns the directory in which the code file is stored, but os.getcwd()
gives you your current working directory which is by default where the code was executed, the latter can be changed using the os.chdir()
command.
- [Django]-Track the number of "page views" or "hits" of an object?
- [Django]-Threaded Django task doesn't automatically handle transactions or db connections?
- [Django]-Where to store secret keys DJANGO
4👍
os.getcwd()
will not give you the path where the settings.py
is located rather it will give you the path from where the script (in your case manage.py
) is executed.
- [Django]-Foreign Key Django Model
- [Django]-Django set range for integer model field as constraint
- [Django]-How to delete project in django
1👍
If the two statements you show truly have the same output, then either should work. So either: 1) they are subtly different, for example, one has a trailing slash, the other doesn’t, or 2) you are testing in one environment and running in another.
- [Django]-How to programmatically call a Django Rest Framework view within another view?
- [Django]-Where is my Django installation?
- [Django]-How to do SELECT COUNT(*) GROUP BY and ORDER BY in Django?