How do I get the path of the Python script I am running in?

The Question :

401 people think this question is useful

In Python, how do I get the path and name of the file that is currently executing?

How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename – not the full path as I do on Windows.

No matter where my application is launched from, I want to open files that are relative to my script file(s).

The Question Comments :
  • It seems that Jeff forgot that not all python scripts are modules, please nominate for reopening.
  • @sorin oh, but they are; a module object can be created for any script file. Just because something never actually gets imported doesn’t make it “not a module”. The answer is the same, anyway: treat the script as a module (use some kind of bootstrap if really necessary) and then apply the same technique.
  • Yes, a script is a module, but this well-asked question should be re-opened. It has not been answered here, and the “duplicate” question is not a duplicate because it only answers how to get the location of a module you have loaded, not the one you are in.
  • see the “import inspect” solution at…
  • @acidzombie24 you don’t need the full path to open and manipulate files from your directory. you can, for example, open('images/pets/dog.png') and Python will do the other.

The Answer 1

510 people think this answer is useful

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

The Answer 2

119 people think this answer is useful

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

The Answer 3

112 people think this answer is useful
import os
print os.path.abspath(__file__)

The Answer 4

42 people think this answer is useful

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you’re planning to do so, this is the functional equivalent:


Py2exe does not provide an __file__ variable. For reference:

The Answer 5

-5 people think this answer is useful

If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.

Of course, there are better solutions, as posted. I just kind of like mine.


Add a Comment