How to get python script directory in Spyder?

The script below find the get the script directory in Spyder and set it to current working directory.

The code relies on the internal variable “_ih” and “_i1” spyder uses when running code inside the editor. They stores the cell number and the script filepath to run it in the console.

The if statement can be used to check if “_i1” has been defined to avoid an error running the script outside spyder.

import os
if '_ih' in vars() or '_ih' in globals():
    script_path = _ih[-1].split("'")[1]
    wdir = os.path.dirname(script_path)
    os.chdir(wdir)
elif '_i1' in vars() or '_i1' in globals():
    script_path = _i1.split("'")[1]
    wdir = os.path.dirname(script_path)
    os.chdir(wdir)

Leave a comment