Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference where a python script is located if being run from another location

I'm trying to run a python script from a different location than where it is located but I need to reference files where the python script is located. I tried the following:

os.chdir(os.getcwd())

But unfortunately that gets the current working dir of where I ran the script from, not where the script currently lives.

Thanks

like image 641
Danny Avatar asked Mar 17 '26 12:03

Danny


1 Answers

You can use

os.path.dirname(__file__)

to get the directory your script is located in.

like image 125
Sven Marnach Avatar answered Mar 19 '26 01:03

Sven Marnach



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!