1

From here: Find current directory and file's directory

I tried in spyder (Python IDE):

dir_path = os.path.dirname(os.path.realpath('__file__'))

and:

cwd = os.getcwd()

I only get like just the user directory and not the location of my source file where I'm coding

My source code is here:

C:\Users\username\test\testerrr\test.py

I only get:

C:\Users\username

I use:

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

and not:

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

else I get this:

os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):

  File "<ipython-input-18-98004a18344a>", line 1, in <module>
    os.path.dirname(os.path.realpath(__file__))

NameError: name '__file__' is not defined

Well, it seems that's works only when we run its through shell.

2 Answers2

1

Try this:

dir_path = os.path.dirname(os.path.realpath(__file__))

not '__file__'. It should be __file__

Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
1

Remove the quotes '__file__' should be __file__.

What you are getting from os.path.realpath('__file__') is $CWD/__file__ which is not what you want. That is why you get $CWD when you call os.path.dirname on that result.

Dan D.
  • 73,243
  • 15
  • 104
  • 123