How do I get the path of the current executed file in Python?
You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.
However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.
some_path/module_locator.py:
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
some_path/main.py:
import module_locator
my_path = module_locator.module_path()
If you have several main scripts in different directories, you may need more than one copy of module_locator.
Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.
How do I get the path and name of the file that is currently executing?
p1.py:
execfile("p2.py")
p2.py:
import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
How do I get the full path of the current file's directory?
The special variable __file__
contains the path to the current file. From that we can get the directory using either pathlib
or the os.path
module.
Python 3
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
Python 2 and 3
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file
is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__
may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.
References
- pathlib in the python documentation.
- os.path - Python 2.7, os.path - Python 3
- os.getcwd - Python 2.7, os.getcwd - Python 3
- what does the __file__ variable mean/do?
Find path to currently running file
__file__
is NOT what you are looking for. Don't use accidental side-effects
sys.argv[0]
is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv
__file__
is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0]
.
Example:
C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
C:\junk\so>\python26\python scriptpath\script1.py
script: sys.argv[0] is 'scriptpath\\script1.py'
script: __file__ is 'scriptpath\\script1.py'
script: cwd is 'C:\\junk\\so'
show_where: sys.argv[0] is 'scriptpath\\script1.py'
show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc'
show_where: cwd is 'C:\\junk\\so'
Getting the full path the script is currently running in [Python]
Let me explain to you by explaining the outputs of all the commands you mentioned by running them in Windows.
Nothing special here, just importing some modules. Importing numpy
to test the commands.
In [1]: import os
...: import sys
...: import numpy
This gives the current working directory in which your process/program is executing. (detailed tutorial here)
In [2]: os.getcwd()
Out[2]: 'C:\\Users\\<username>'
This tells which file the module is loaded from which file.
In [3]: numpy.__file__
Out[3]: 'C:\\Users\\<username>\\anaconda3\\lib\\site-packages\\numpy\\__init__.py'
The path of the loaded file for the module, it can be a relative path.
In [4]: os.path.dirname(numpy.__file__)
Out[4]: 'C:\\Users\\Punit Singh\\anaconda3\\lib\\site-packages\\numpy'
The actual path of the loaded file for the module. See the difference from previous in lib
and Lib
. The folder name actually starts from the capital letter.
In [5]: os.path.dirname(os.path.realpath(numpy.__file__))
Out[5]: 'C:\\Users\\Punit Singh\\anaconda3\\Lib\\site-packages\\numpy'
This is the absolute path, you'll see the difference when you'll run this in Linux. It starts with the root folder denoted by \
.
In [6]: os.path.dirname(os.path.abspath(numpy.__file__))
Out[6]: 'C:\\Users\\Punit Singh\\anaconda3\\lib\\site-packages\\numpy'
[7]
and [8]
respectively give the path and absolute path of the file which is currently executing, here sys.argv[0]
returns the file which is currently executing, since currently, I am running ipython, it is ipython.exe shown in [9]
. (detailed tutorial here)
In [7]: os.path.dirname(sys.argv[0])
Out[7]: 'C:\\Users\\<username>\\anaconda3\\Scripts'
In [8]: os.path.abspath(os.path.dirname(sys.argv[0]))
Out[8]: 'C:\\Users\\<username>\\anaconda3\\Scripts'
In [9]: sys.argv[0]
Out[9]: 'C:\\Users\\<username>\\anaconda3\\Scripts\\ipython'
This gives the absolute path of the executable binary for the Python interpreter (documentation here)
In [10]: sys.executable
Out[10]: 'C:\\Users\\Punit Singh\\anaconda3\\python.exe'
Now coming to your requirement, I understand that you need to access files where this ipython.exe
as shown in [9]
is located, so you can use commands mentioned in [7]
or [8]
.
Find the current directory and file's directory
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir()
to change your current working directory, since the value of the __file__
constant is relative to the current working directory and is not changed by an os.chdir()
call.)
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The
os
andos.path
modules. - The
__file__
constant os.path.realpath(path)
(returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path)
(returns "the directory name of pathnamepath
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory topath
")
Get name of current script in Python
You can use __file__
to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.
If you want to omit the directory part (which might be present), you can use os.path.basename(__file__)
.
How do I find out the path of the currently executing script?
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.
Related Topics
Rename Multiple Files in a Directory in Python
Comparing Two Numpy Arrays for Equality, Element-Wise
Convert Array of Indices to One-Hot Encoded Array in Numpy
Plotting in a Non-Blocking Way with Matplotlib
What Are Logits? Differencebetween Softmax and Softmax_Cross_Entropy_With_Logits
Determine Function Name from Within That Function (Without Using Traceback)
How to Extract the Decision Rules from Scikit-Learn Decision-Tree
How to Get the Named Parameters from a Url Using Flask
How to Load Default Profile in Chrome Using Python Selenium Webdriver
Python Threading Multiple Bash Subprocesses
How to Highlight Text in a Tkinter Text Widget
Index a 2D Numpy Array with 2 Lists of Indices
Importerror: Dll Load Failed: the Specified Module Could Not Be Found
Writing a Connection String When Password Contains Special Characters