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?
__file__
at some point?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.__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?__file__
too. Please run python scripts using thepython3
executable. Don't trust IDE or even the python's REPL to be 100% equivalent to running a scriptos.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.