Python – Locate Path of Python Script Within Script

When running a python script it is many times beneficial to know where on the system the python file you are running is located, for instance if you have files in the same directory as your script that you need to read from or write to but you wont always know where your script will be run from. This can be done very easily through the ‘os’ module. Below is an example of a script that will do nothing but print out the absolute path of the python file so if you run this script in any directory on the system it will give you the absolute path that it is located.


As you can see line 10 is getting the absolute path of the file and storing it in a variable ‘absolute_path’ and line 12 is displaying that to the user. A good exercise now would be to move your python file around to different folders on your system and run the file and you can see how the output will change based on the directory the file is run from.

Leave a Comment