Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spyder/Python - Automatically set working directory to current script's

I know that the directory can be automatically changed to that of the current script if we press F5.

But is there a way to automatically do so when I run the codes in interactive mode, or when I open a script? Currently I need to os.chdir() to the current working directory.

Thanks.

like image 762
Quy Vu Xuan Avatar asked Mar 09 '26 17:03

Quy Vu Xuan


1 Answers

You can add the following lines to your script:

import os
os.chdir(os.path.dirname(__file__))

__file__ will return the path of the script, and we can use os.path.dirname to find which directory it is located in. Then just use os.chdir to change to that directory.

like image 146
keineahnung2345 Avatar answered Mar 11 '26 07:03

keineahnung2345



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!