So I have a python file sample.py which is in let's say 'A/B/C' and my current working directory is let's say 'D/E'. Now in sample.py I am needed it's directory that is 'A/B/C' . Can anyone help me with this. I have tried "dir_path = os.path.dirname(os.path.realpath('__sample__'))"
but it returns the current working directory.
Asked
Active
Viewed 177 times
-1

joedenly
- 383
- 2
- 5
- 14
1 Answers
0
Change the line:
dir_path = os.path.dirname(os.path.realpath('__sample__'))
to
dir_path = os.path.dirname(os.path.realpath(__file__))
This should work for you. Find more about __file__
here.

squareRoot17
- 820
- 6
- 16
-
Your answer is assuming that the script is imported. Also you might want to consider flagging the question as a duplicate instead of duplicating an answer. – gstukelj Nov 24 '19 at 13:45
-
@gst well that's what the question interprets. Also, for the flagging part, I've flagged it already. However, it seems that the user has some misunderstanding about the accepted answer of the question you're referring to. – squareRoot17 Nov 24 '19 at 13:52