SoFunction
Updated on 2024-12-12

How to completely solve python NameError:name '__file__' is not defined

Background to the issue

I created a function that contains a code to get the path to the currently executing file

current_path = ((__file__))

I put this code in the middle of the function (the part that has been commented out in the image).

When executing a python file in a CMD window, it reports NameError: name 'file' is not defined error. (Also executed in linux, same error)

After looking up a few options (e.g., shown below), there is talk of changing __file__ to 'file' (this is simply bullshit), and the one that says to change it to () (which gets the current path of the executed command).

Tested these scenarios and was not able to get the absolute path to the current executable.

prescription

Because before this code of mine was executing fine, after changing it I got this error.

After a night of various Baidu's and pondering, I put this code at the very beginning of the function early the next morning. And then the test worked! Success! Success!

This code will get the path to the current file normally without reporting an error!

Record your own path through the pit so that those who encounter the same pit can jump out as soon as possible!

summarize

to this article on how to completely solve the python NameError: name '__file__' is not defined article is introduced to this, more related python NameError: name __file__ is not defined content please search for my previous posts or continue to browse the following relevant I hope you will support me more in the future!