corr
corr

Reputation: 73

NameError: __file__ is not defined

I'm trying to build a relative path. When running the following line in my .py script

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

I get a name error. It used to work just a few days ago when I set it up but now it doesn't any longer. I am not executing this in my shell, just running my script as usually.

 os.path.dirname(sys.argv[0]) 

only returns an empty string. When I use "__file__" instead, it returns the home directory but not the path to my file. I thought __file__ is set to the filepath as soon as I load a module in my script. Anyone know where I'm going wrong?

More info: my .py script is in a folder in "C:/Users/corr/Documents/Uni/Thesis/Code/" I want to construct a relative path so I can access the data files in folder "C:/Users/corr/Documents/Uni/Thesis/Data/". When I set up the script, the following lines worked:

this_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(this_path, "../Data")

Now though, when I run the first line I get a NameError: __file__ not defined. When I run the same line with "__file__" instead, it returns "C:\Users\corr". Also, I am executing my script in the Spyder environment, as this is where I usually work.

Upvotes: 0

Views: 6096

Answers (1)

Davis Herring
Davis Herring

Reputation: 39748

__file__ is set for modules, not scripts, which are supposed to use sys.argv[0]. (In some cases, argv[0] is the basename used to find a program via PATH.) Spyder apparently sets it to an empty string instead (or, in one buggy version sets argv to an empty list), so you might have to do silly things like

def f(): pass
print(f.__code__.co_filename)

Meanwhile, using "__file__" (the string literal) just means a file by that name. path.dirname returns an empty string for it (since it has no slashes), which many Python functions (like abspath) interpret to mean the current working directory (which for Spyder is evidently your home directory).

Upvotes: 2

Related Questions