Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • Agreed! Sorry it took my a while to come around to it; I had taken a bit of a break from the code that used I need this for. But after much deliberation, os.getcwd() did exactly what I needed and not file, which instead gave me the name of the file that function was in (not the file being run). Commented Sep 11, 2009 at 0:07
  • 5
    As a note, if you're looking for the path to the file that holds the specific line of code being run, __file__ is the one to use. (Such as, an __init__.py where you don't know where it's going to live and need to add it's dirname() to sys.path when that module is imported...) Commented Mar 31, 2012 at 1:37
  • 1
    @MarkRibau: Your first sentence is true but superflous (that's what __file__ is defined to be). Your 2nd sentence is nothing to with the question, and is extremely puzzling: if you don't know where a module is, you can't import it, and if you can't import it you can't get its __file__ ... Commented Mar 31, 2012 at 7:09
  • 1
    @JohnMachin "currently running python script" is a vague question. Currently running line? Currently running __main__? Which is why I clarify that if you intend currently running line, __file__ is correct. Commented Apr 2, 2012 at 23:57
  • @JohnMachin Also, you can import any module that is on sys.path without knowing it's path. HOWEVER, some modules (such as p4python) require it's own path to be in sys.path. I felt it silly to go around and modify everyone's systems to have that in their environment, so instead I made an __init.py__ that will do it automatically no matter where their project root is. We do not require our developers to have identical locations for the project root, as different contractors have different hardware / harddrive capacities. Commented Apr 2, 2012 at 23:58