Hello, I am pretty unfamiliar with coding in general, but have been coding via spyder for a university unit this past semester. All semester in every class, we have started our scripts with these initial 3 lines:
import os
script_directory = os.path.dirname(os.path.abspath(file))
os.chdir(script_directory)
Not sure why, but as of today, every time I go to run these lines I hvae the message:
Cell In[36], line 1
----> 1 script_directory = os.path.dirname(os.path.abspath(file))
NameError: name ‘file’ is not defined
appear in my console.
I am completely confused as to why this is the case considering I have not changed my code whatsoever since yesterday when it was working just fine.
The reason that you’re getting an error is because the argument to os.path.abspath is expecting a string argument that represents a path to a file not just the word file that has not been assigned a value. If you assign a string value to the word file to, say, for example: file = "/Desktop/myfile.txt" first, you should be ok (or anything similar).
Passing the argument file without it first being assigned a string value will generate an exception (i.e., error) as it shouldt.
The variable file is not defined. You need to define it like this:
import os
file = "c:\myprogram\myfile.txt"
script_directory = os.path.dirname(os.path.abspath(file))
os.chdir(script_directory)
And why are you changing the directory when you are already in that directory? That seems unnecessary.
What are you trying to achieve? This looks like a stub program, or template for other programs that you always start with.
Help us help you. Read this link first and learn how to format code so we can help you better. Formatting code Do not use a screen shot of your code, instead paste your code in as preformatted code, as some of us will copy and paste the code to get it to work for you, so you can learn from this. You will get more help this way.