3

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

I would like to find out the path to the currently executing script. I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.

Community
  • 1
  • 1
Ashy
  • 2,014
  • 5
  • 21
  • 25
  • Thanks Ray, I did do a search before I asked but never found that. *shrug* :) – Ashy Jan 14 '09 at 20:27
  • not a big deal; it has happened to me as well: http://stackoverflow.com/questions/168730/how-do-i-loop-through-all-files-in-a-folder-using-python-closed – Ray Jan 14 '09 at 20:55

2 Answers2

8

In Python, __file__ identifies the current Python file. Thus:

print "I'm inside Python file %s" % __file__

will print the current Python file. Note that this works in imported Python modules, as well as scripts.

Brian Clapper
  • 25,705
  • 7
  • 65
  • 65
1

How about using sys.path[0]

You can do something like
'print os.path.join(sys.path[0], sys.argv[0])'

https://docs.python.org/library/sys.html

twasbrillig
  • 17,084
  • 9
  • 43
  • 67
Epitaph
  • 3,128
  • 10
  • 34
  • 43
  • Unlikely to actually be correct -- the running script may not be the first item on the path. It could be in any of the locations on the PYTHONPATH. Further, if it was started with python -m someModule, then argv[0] isn't relevant, either. – S.Lott Jan 14 '09 at 19:51
  • @S.Lott - From the docs that Pat linked: "the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter." so it should be correct for what I want but I have decided to use os.path.abspath(__file__) :) – Ashy Jan 14 '09 at 20:32