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), 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 :
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 =', sys.argv)
pathname = os.path.dirname(sys.argv)
print('path =', pathname)
print('full path =', os.path.abspath(pathname))
The Answer 3
112 people think this answer is useful
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: http://www.py2exe.org/index.cgi/Py2exeEnvironment
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.