Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a python script aware of its stored location path?

Tags:

python

/home/bar/foo/test.py:

I am trying test.py to print /home/bar/foo irrespective of from where I run the script from:

import os
def foo():
  print os.getcwd()

test run:

[/home/bar $] python /home/bar/foo/test.py        # echoes /home/bar
[/tmp $] python /home/bar/foo/test.py             # echoes /tmp

os.getcwd() not the function for the task. How can I get this done otherwise?

like image 801
Vaibhav Bajpai Avatar asked May 02 '26 08:05

Vaibhav Bajpai


1 Answers

Try this:

import os.path
p = os.path.abspath(__file__)
like image 164
Manny D Avatar answered May 04 '26 22:05

Manny D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!