1

I've been trying to get the location of an open .py file (using Spyder) that will be used to link various files and use the __file__ name so that any machine can run from its current directory.

The problem is that when I try:

location = os.path.abspath(os.path.dirname(__file__))

It gives me the error:

NameError: name '__file__' is not defined

I bypassed this by calling on the file as a string rather than the name file variable using:

location = os.path.abspath(os.path.dirname('__file__'))

This worked for getting me the parent directory of the file but not the actual folder that the file was in:

location = 'C:\Users\......\Scripts'

When really the location is in:

location = 'C:\Users\......\Scripts\ISO'

I've tried various combinations of abspath and dirname and realpath to get the true directory that the file is in but I cannot get it.

What am I doing incorrectly?

6
  • 1
    it doesn't work in builtin modules or in interactive shell. What is your context? did you delete __file__ at some point? Dec 6, 2018 at 17:42
  • os.path.dirname('__file__') returns blank. it just computes the dirname of a filename, which is empty string, and absolute path on that returns the current directory. Dec 6, 2018 at 17:43
  • No, __file__ still exists in the original directory from which it was downloaded. This file was opened using Spyder from opening in the directory if that's what you're asking? Dec 6, 2018 at 17:46
  • 4
    @HelloToEarth You are using Spyder interactive shell? That probably does not define __file__ too. Please run python scripts using the python3 executable. Don't trust IDE or even the python's REPL to be 100% equivalent to running a script
    – Bakuriu
    Dec 6, 2018 at 17:58
  • 3
    FYI: if you are in an interactive session you can simply use os.getcwd() to get the current directory. There is no __file__ because you are not executing a file... you are interactively creating commands, so there is no point in having __file__ around.
    – Bakuriu
    Dec 6, 2018 at 17:59

1 Answer 1

0

Because I was running the script inside the Spyder shell it did not output the proper working directory because the working directory settings were somehow misaligned with the file's path.

This can be solved by Run -> Configuration per file -> The directory of the file being executed

But the more effective way of running the script using __file__ is to run the script from the python3.X.exe file in the directory which the script is located.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.