alpha
alpha

Reputation: 393

How to get the directory of a current script on Spyder (without using '__file__')?

When I open Spyder (version 4.1.4), it opens a script that I was previously working with. However, the directory is set to 'C:\\Users\\UserName' (this is what I get with os.getcwd()).

I like to change the directory to where the script is, but I couldn't find a simple way to get the directory of the script and use os.chdir(path).

As it's mentioned here, os.path.dirname(__file__) gives NameError: name '__file__' is not defined when I run it on Spyder console, and I like to get the path without running the whole script.

In Spyder, what command(s) can I use to find a currently opened script?

Upvotes: 2

Views: 1076

Answers (1)

Joan Barreto
Joan Barreto

Reputation: 36

I haven't found a solution either. This is the way I deal with it on Windows:

  1. Select and comment the whole script (Ctrl + a + Ctrl + 1)
  2. Run file (F5)
  3. Uncomment or undo (Ctrl + z).

At least in my case, the current directory changes to that of the script.

Upvotes: 2

Related Questions