419
votes

Duplicate:
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).

5
It seems that Jeff forgot that not all python scripts are modules, please nominate for reopening. - sorin
@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. - Karl Knechtel
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. - Ben Bryant
see the "import inspect" solution at stackoverflow.com/questions/50499/… - Ben Bryant
@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. - Alba Mendez

5 Answers

538
votes

Use this to get the path of the current file. It will resolve any symlinks in the path.

import os

file_path = os.path.realpath(__file__)

This works fine on my mac.

126
votes

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)) 
124
votes
import os
print os.path.abspath(__file__)
42
votes

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:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

-5
votes

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.