0

I want to get absolute directory path of python file, not current working Directory.

Suppose I have app.py in '/home/user/coding/python/' directory.

Code of app.py is:

# app.py
import os
print(os.getcwd())
  • I have been in '/home/user/coding/python/' directory I ran python app.py and got
/home/user/coding/python/
  • Now I changed dir cd to /home/user/ and ran python '/home/user/coding/python/app.py' and got
/home/user
  • But I want the python script to print while running python '/home/user/coding/python/app.py'
/home/user/coding/python/

with python command which means the directory of that python file.

How can I do that?

Shezan
  • 277
  • 2
  • 8

1 Answers1

1
#app.py
import os

print(os.path.dirname(os.path.realpath(__file__)))

will print

/home/user/coding/python.

If you require the separator at the end:

#app.py
import os

print(os.path.join(os.path.dirname(os.path.realpath(__file__))) + os.path.sep)

will print

/home/user/coding/python/.

Kamil Wozniak
  • 430
  • 3
  • 7