How do I get the path of the Python script I am running in? [duplicate]
Asked Answered
S

5

519

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

Sputter answered 27/2, 2009 at 15:50 Comment(8)
It seems that Jeff forgot that not all python scripts are modules, please nominate for reopening.Chickenhearted
@Chickenhearted 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.Coetaneous
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.Iniquitous
see the "import inspect" solution at #50999Iniquitous
@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.Wildwood
I have a one line solution over here: #2632699Eames
I have changed the duplicate links so that they point at actual duplicate questions - this question does not need to be reopened.Eames
Simpler solution with explanation what is pwd hinty.io/brucehardywald/python-create-folderNostril
C
642

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. It won't work from the Python interpreter (you need to be executing a Python file).

Chin answered 27/2, 2009 at 15:56 Comment(18)
Not so sure about that, here a result from OSX 10.6 NameError: global name '__file__' is not definedChickenhearted
Sorin: Perhaps you tried the expression in the shell?Coffeecolored
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 definedLinea
Make a chdir before calling realpath and real path will fail, this is not the answer.Chickenhearted
@Linea It's __file__, not file. Does changing that fix it?Wombat
@Wombat 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 :)Linea
The NameError: global name '__file__' is not defined error just means you forgot to import os.Cystitis
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__)Maillot
When I execfile("script.py") then inside script.py __file__ is not defined, but it is when I import script.Vivisectionist
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)Andantino
NameError: __file__ ... And I have imported os. Not sure why this is the accepted answer..?Inrush
This will not work in shell.Waterless
The path contains the file name at the end, it's not just the path :-(Coorg
same issue not working as sorin's commentItself
works fine in a script on GNU/Linux with Python3.XAdduce
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 tooTreatise
Does this resolve symlinks of symlinks of symlinks, etc.?Undercut
Works fine when you are running it in a script, not in the IDLE editorMandolin
I
172
import os
print os.path.abspath(__file__)
Inception answered 27/2, 2009 at 15:52 Comment(4)
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.Coverage
This should be combined with information in the other answer: os.path.abspath(os.path.dirname(__file__)) will give the directory.Cloister
Thank you. Does it work for you on jupyter notebook?Bookout
this topic to work on notebookOpportune
W
149

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)) 
Willenewillet answered 27/2, 2009 at 15:52 Comment(9)
I like how your answer shows a lot of different variations and features from python to solve the question.Draconian
Yes, and I like it better because it doesn't use __ variables (I know it's just a convention for system names)Bronze
This does not work if you call the script via another script from another directory.Chickenhearted
That's probably something we should tell the author.Willenewillet
@SorinSbarnea I see it does not work if we call it from another script in another directory. Then what is the solution?Avantgarde
@SorinSbarnea see the subject of the question: get the path of the running script (the script which has been executed). An imported module is just a resource.Wildwood
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".Chickenhearted
This does also not work on UNIX if the script is in your PATH!Merchant
@Chickenhearted 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.Undercut
E
60

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

Extravehicular answered 26/3, 2010 at 19:39 Comment(4)
Unluckily this does not work on Mac, as the OP says. Please see sys.argv: it is operating system dependent whether this is a full pathname or notNath
(it's incredibly complex to get a really cross-browser solution...)Nath
@Nath that's not a problem. To make sure it's an absolute (full) pathname, use os.path.abspath(...)Wildwood
this doesn't give the location of the .py file of interest when I use a jupyter notebookLysine
M
-7

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.

Maravedi answered 27/2, 2009 at 15:54 Comment(2)
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)Bronze
question was how to obtain the module's path, not how to build one pathname from anotherIniquitous

© 2022 - 2024 — McMap. All rights reserved.