1

I have the following:

% more a.py 
import os
os.system('pwd')

% python a.py 
/Users/yl/test/f

% cd ..

% python ./f/a.py 
/Users/yl/test

Basically I want the last output to be "/Users/yl/test/f", which is the path where the script is located (not where python was invoked). Have played around but didn't find a good solution. Thanks for any suggestions!

Cat Plus Plus
  • 119,938
  • 26
  • 191
  • 218
Hailiang Zhang
  • 15,674
  • 21
  • 65
  • 112

2 Answers2

2
import os
app_dir = os.path.dirname(__file__)
print(app_dir)
Cat Plus Plus
  • 119,938
  • 26
  • 191
  • 218
2
import os
print (os.path.dirname(os.path.abspath(__file__)))
ekhumoro
  • 107,367
  • 18
  • 208
  • 308