Pycharm "__file__ is not defined"
I'm having a possibly noob problem.
I have a python script that I'm running in scientific mode. When I run a cell where it is supposed to print(__file__). it gives the following error.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-2ee247ea65df>", line 1, in <module>
out = OutputTag('dataload', __file__)
NameError: name '__file__' is not defined
However, when I right click the script file and run the whole thing, this error disappears, but I'm getting other strange problems.
It can't find any of my files to read. For example I have a file in :
ProjectFolder/Data/data.csv
and I'm reading it using:
pd.read_csv("Data/data.csv").
I need to change it to
pd.read_csv("../Data/data.csv").
But when doing so it breaks now when I run it by right clicking on the file and running the whole thing.
I'm sure it's some problem with how I have things configured.
Please sign in to leave a comment.
>I have a python script that I'm running in scientific mode. When I run a cell where it is supposed to print(__file__). it gives the following error.
Did you execute all the above cells before this cell? If this doesn't help, please provide code sample.
yes, I made sure to execute the above code.
The project structure is that this python file is in Project/Chapter1/chapter1.py
the csv is in Project/Data/data.csv
When I right click on the file name tab at the top of the window and choose run chapter1, the print statement works, but the load data gives an error. I can fix that error by making changing it to data=pd.read_csv('../Data/data.csv')
However, running the code cell by cell by control enter, or by clicking the little green play button by the cell, the print statement gives an error saying "__file__ is not defined", but the original load works fine (without the ../)
The __file__ attribute is set automatically when you run the file, but it's not set when you run interactively, as the case with cell-based execution.
>I can fix that error by making changing it to data=pd.read_csv('../Data/data.csv')
This has likely to do with working directory in your run/debug configuration. Make sure the working directory is the same as your script path.