0

Actually I found the solution of my main problem "Get the full path to the directory a Python file is contained in" from the previous answer : Find current directory and file's directory.

And the code below from the answer works well if I run my entire script, in other words, hotkey F5.

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

However, if I just select the two lines of the above code and run it, in other words, hotkey F9. Then I will receive the error below:

NameError: name '__file__' is not defined

So if anyone happens to know why the error occurs, please give a brief explanation.

Thanks a lot!

By the way, i used Spyder (Python 2.7).

a_guest
36.7k15 gold badges75 silver badges137 bronze badges
asked Jun 29, 2017 at 13:41

1 Answer 1

1

Inside Spyder or any interactive python process, the constant __file__ is not defined.

When you run the whole script, Spyder basically run the following command:

$ python script.py

While, if you select those two lines, it's more like entering a interactive python process first, then interpret the statements:

$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44) 
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os 
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>> 

That's the difference.

answered Jun 29, 2017 at 13:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.