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
  • So is the output you showed the value of dir_path or cwd? Why do you even retrieve the cwd? Commented Apr 22, 2018 at 12:43
  • 2
    '__file__' should be __file__. Commented Apr 22, 2018 at 12:45

2 Answers 2

1

Try this:

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

not '__file__'. It should be __file__

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Where are you running the code? In the REPL? It only works in a module as that is where __file__ is defined by the import process.
spyder (Python IDE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.