416

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

dddJewelsbbb
  • 576
  • 2
  • 16
  • 23
    It seems that Jeff forgot that not all python scripts are modules, please nominate for reopening. – sorin Nov 22 '11 at 11:26
  • @sorin oh, but they are; a `module` object can be created for any script file. Just because something never actually gets `import`ed 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 Dec 26 '11 at 07:10
  • 8
    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 Jan 19 '12 at 18:38
  • 3
    see the "import inspect" solution at http://stackoverflow.com/questions/50499/in-python-how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executin – Ben Bryant Jan 19 '12 at 18:55
  • @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 Jul 13 '12 at 08:15
  • I have a one line solution over here: http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python/18489147#18489147 – ArtOfWarfare Jun 10 '14 at 13:01
  • I have changed the duplicate links so that they point at actual duplicate questions - this question does not need to be reopened. – ArtOfWarfare Jun 10 '14 at 13:09
  • Simpler solution with explanation what is pwd https://hinty.io/brucehardywald/python-create-folder/ – Ivan Borshchov Oct 22 '20 at 11:04

5 Answers5

534

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.

Alan W. Smith
  • 21,861
  • 3
  • 64
  • 88
jblocksom
  • 12,545
  • 5
  • 32
  • 30
  • 22
    Not so sure about that, here a result from OSX 10.6 `NameError: global name '__file__' is not defined` – sorin Apr 13 '10 at 15:40
  • 19
    Sorin: Perhaps you tried the expression in the shell? – André Laszlo May 28 '10 at 15:44
  • 4
    I get the same and using it in a program not in the shell. File "C:\Python27\pydocs\cli_mate new\chimpbot.py", line 15, in __init__ self.current_dict = os.path.realpath(__file__)+'\data\default_dict.dat' NameError: global name '__file__' is not defined – Mr_Chimp Jan 16 '11 at 15:00
  • 15
    Make a `chdir` before calling `realpath` and real path will fail, this is not the answer. – sorin Nov 22 '11 at 11:27
  • @Mr_Chimp It's `__file__`, not `file`. Does changing that fix it? – jpmc26 Feb 10 '14 at 23:05
  • 2
    @jpmc26 I think the underscores got turned into bold formatting... That was three years ago though. I don't even remember what I was using this for :) – Mr_Chimp Feb 11 '14 at 13:12
  • 7
    The `NameError: global name '__file__' is not defined` error just means you forgot to `import os`. – Fabien Snauwaert May 12 '14 at 12:26
  • I noticed that if you put `os.chdir('somewhere/else/')` before hand, it somehow won't get the correct path. E.g. `os.chdir('..'); print os.path.realpath(__file__)` – Jason Oct 27 '16 at 06:33
  • When I `execfile("script.py")` then inside `script.py` `__file__` is not defined, but it is when I `import script`. – christianbrodbeck Nov 11 '16 at 14:07
  • 2
    It may be worth adding that this only works if we're really excecuting the script, thus it doesn't work when just running the cell (e.g. in Spyder) – poppie Nov 16 '16 at 04:38
  • 7
    `NameError: __file__` ... And I *have* imported `os`. Not sure why this is the accepted answer..? – Frans Aug 12 '17 at 17:34
  • 5
    This will not work in shell. – Jakub Bláha Jan 02 '18 at 09:42
  • The path contains the file name at the end, it's not just the path :-( – jeancallisti Apr 16 '19 at 10:35
  • same issue not working as sorin's comment – BHS Jul 22 '19 at 23:23
  • works fine in a script on GNU/Linux with Python3.X – Harry S Nov 11 '19 at 12:05
  • works fine on my osx python3 and ubuntu, this anwser should be pushed on top, it maybe required python3 this should be added to the awnser too – Peko Chan Jun 16 '20 at 08:02
126

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)) 
Bilal Syed Hussain
  • 6,824
  • 8
  • 31
  • 41
Jon W
  • 14,320
  • 6
  • 35
  • 46
  • 2
    I like how your answer shows a lot of different variations and features from python to solve the question. – Jeremy L Feb 27 '09 at 15:54
  • Yes, and I like it better because it doesn't use `__` variables (I know it's just a convention for system names) – Davide Nov 17 '09 at 19:13
  • 136
    This **does not work** if you call the script via another script from another directory. – sorin Apr 13 '10 at 15:37
  • 4
    That's probably something we should tell the author. – Jon W Apr 13 '10 at 20:40
  • @SorinSbarnea I see it does not work if we call it from another script in another directory. Then what is the solution? – Rohit Banga Jun 18 '12 at 21:41
  • 3
    @SorinSbarnea see the subject of the question: get the path of the **running** script (the script which has been executed). An `import`ed module is just a resource. – Alba Mendez Jul 13 '12 at 08:11
  • 1
    The question is not very clear, but your solution would work only if it is called at the beginning of the script (in order to be sure that nobody changes the current directory). I am inclined to use the inspect method instead. "running script" is not necessarily same as "called script" (entry point) or "currently running script". – sorin Jul 13 '12 at 12:27
  • 1
    This does also not work on UNIX if the script is in your PATH! – Alexander Oh Mar 15 '13 at 13:49
  • @sorin and Alex Please tell us how it does not work. If we know what it does do, that should help us to find a real solution. – Brōtsyorfuzthrāx Sep 10 '14 at 21:24
122
import os
print os.path.abspath(__file__)
Jason Coon
  • 15,401
  • 9
  • 38
  • 50
  • 7
    Thanks. This get the path of the .py file where the code is written, which is what I want, even though OP wanted another path. – OdraEncoded Dec 15 '17 at 21:44
  • 6
    This should be combined with information in the other answer: `os.path.abspath(os.path.dirname(__file__))` will give the directory. – Jim Oldfield Feb 07 '21 at 12:45
42

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

Dan
  • 495
  • 5
  • 6
  • 3
    Unluckily this does not work on Mac, as the OP says. Please see [sys.argv](http://docs.python.org/library/sys.html#sys.argv): _it is operating system dependent whether this is a full pathname or not_ – Stefano Feb 09 '12 at 10:17
  • 1
    (it's incredibly complex to get a really cross-browser solution...) – Stefano Feb 09 '12 at 11:08
  • 7
    @Stefano **that's not a problem**. To make sure it's an absolute (full) pathname, use `os.path.abspath(...)` – Alba Mendez Jul 13 '12 at 08:06
  • 1
    this doesn't give the location of the .py file of interest when I use a jupyter notebook – AsheKetchum Apr 15 '19 at 22:29
-5

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.

Chris Lutz
  • 66,621
  • 15
  • 121
  • 178
  • 5
    In python this does not work if you call the script from a completely different path, e.g. if you are in `~` and your script is in `/some-path/script` you'll get `./` equal to `~` and not `/some-path` as he asked (and I need too) – Davide Nov 17 '09 at 19:01
  • 2
    question was how to obtain the module's path, not how to build one pathname from another – Ben Bryant Jan 19 '12 at 17:24