How to get the original script directory in python

Python and so any other programming language has its issues, and the one i am meaning today is, what is the script is run from another path? That semms no problem at all, right? well yes, but actually no, what is the problem in this case is if you are going to use any file at all, in some cases, if running the script from another path like ~home/project1, stead of ~home/project2 who is where the script is, and the script uses anything like “./” to get into files, he will get files from project1 and not from the right location, so the quick fix is:

import os

# Get the path of the script (with script name) __file__ is just the name of the script btw.
script_root = os.path.abspath(__file__)

# Removes the script name and last /
script_dir = os.path.dirname(script_root)

# i did print but do something more usefull with it
print(script_dir, "\n", script_root)

Remenber!

allways use like this:

script_dir+"/filename.something"

never ever try to do:

script_dir+"filename.something"

why you may ask? the first one returns: /home/blabla/foo/filename.something, and the other just: /home/blabla/foofilename.somthing, as you can see you can delete something from someone or edit something from another place accidentally

Leave a Comment