python – How do I get the path and name of the file that is currently executing?

The Question :

495 people think this question is useful

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let’s say I have three files. Using execfile:

  • calls
  • In turn, calls

How can I get the file name and path of, from code within, without having to pass that information as arguments from

(Executing os.getcwd() returns the original starting script’s filepath not the current file’s.)

The Question Comments :

The Answer 1

263 people think this answer is useful


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

The Answer 2

578 people think this answer is useful

as others have said. You may also want to use os.path.realpath to eliminate symlinks:

import os


The Answer 3

91 people think this answer is useful

Update 2018-11-28:

Here is a summary of experiments with Python 2 and 3. With – runs – runs lib/
lib/ – prints filepath expressions

| Python | Run statement       | Filepath expression                    |
|      2 | execfile            | os.path.abspath(inspect.stack()[0][1]) |
|      2 | from lib import bar | __file__                               |
|      3 | exec                | (wasn't able to obtain it)             |
|      3 | import      | __file__                               |

For Python 2, it might be clearer to switch to packages so can use from lib import bar – just add empty files to the two folders.

For Python 3, execfile doesn’t exist – the nearest alternative is exec(open(<filename>).read()), though this affects the stack frames. It’s simplest to just use import foo and import – no files needed.

See also Difference between import and execfile

Original Answer:

Here is an experiment based on the answers in this thread – with Python 2.7.10 on Windows.

The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax, i.e. –

print os.path.abspath(inspect.stack()[0][1])                   # C:\filepaths\lib\
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:\filepaths\lib

Here’s to these being added to sys as functions! Credit to @Usagi and @pablog

Based on the following three files, and running from its folder with python (also tried execfiles with absolute paths and calling from a separate folder).

C:\filepaths\ execfile('')
C:\filepaths\ execfile('lib/')

import sys
import os
import inspect

print "Python " + sys.version

print __file__                                        #
print sys.argv[0]                                     #
print inspect.stack()[0][1]                           # lib/
print sys.path[0]                                     # C:\filepaths

print os.path.realpath(__file__)                      # C:\filepaths\
print os.path.abspath(__file__)                       # C:\filepaths\
print os.path.basename(__file__)                      #
print os.path.basename(os.path.realpath(sys.argv[0])) #

print sys.path[0]                                     # C:\filepaths
print os.path.abspath(os.path.split(sys.argv[0])[0])  # C:\filepaths
print os.path.dirname(os.path.abspath(__file__))      # C:\filepaths
print os.path.dirname(os.path.realpath(sys.argv[0]))  # C:\filepaths
print os.path.dirname(__file__)                       # (empty string)

print inspect.getfile(inspect.currentframe())         # lib/

print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\filepaths\lib\
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\filepaths\lib

print os.path.abspath(inspect.stack()[0][1])          # C:\filepaths\lib\
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:\filepaths\lib

The Answer 4

72 people think this answer is useful

I think this is cleaner:

import inspect
print inspect.stack()[0][1]

and gets the same information as:

print inspect.getfile(inspect.currentframe())

Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.

print inspect.stack()[1][1]

would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.

The Answer 5

48 people think this answer is useful
import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only

The Answer 6

37 people think this answer is useful

The suggestions marked as best are all true if your script consists of only one file.

If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let’s assume this is in a file named

import inspect

print inspect.stack()[-1][1]

Because the last thing ([-1]) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).

Then in file if you import foo it’ll print, rather than, which would be the value of all of these:

  • __file__
  • inspect.getfile(inspect.currentframe())
  • inspect.stack()[0][1]

The Answer 7

14 people think this answer is useful
import os
print os.path.basename(__file__)

this will give us the filename only. i.e. if abspath of file is c:\abcd\ then 2nd line will print

The Answer 8

14 people think this answer is useful

It’s not entirely clear what you mean by “the filepath of the file that is currently running within the process”. sys.argv[0] usually contains the location of the script that was invoked by the Python interpreter. Check the sys documentation for more details.

As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to

the file from which the module was loaded, if it was loaded from a file

The Answer 9

11 people think this answer is useful

I have a script that must work under windows environment. This code snipped is what I’ve finished with:

import os,sys
PROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0])

it’s quite a hacky decision. But it requires no external libraries and it’s the most important thing in my case.

The Answer 10

10 people think this answer is useful

Try this,

import os

The Answer 11

8 people think this answer is useful
import os

No need for inspect or any other library.

This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.

The Answer 12

8 people think this answer is useful

The __file__ attribute works for both the file containing the main execution code as well as imported modules.


The Answer 13

6 people think this answer is useful
import sys

print sys.path[0]

this would print the path of the currently executing script

The Answer 14

6 people think this answer is useful

Since Python 3 is fairly mainstream, I wanted to include a pathlib answer, as I believe that it is probably now a better tool for accessing file and path information.

from pathlib import Path

current_file: Path = Path(__file__).resolve()

If you are seeking the directory of the current file, it is as easy as adding .parent to the Path() statement:

current_path: Path = Path(__file__).parent.resolve()

The Answer 15

5 people think this answer is useful

I think it’s just __file__ Sounds like you may also want to checkout the inspect module.

The Answer 16

4 people think this answer is useful

You can use inspect.stack()

import inspect,os
inspect.stack()[0]  => (<frame object at 0x00AC2AC0>, 'g:\\Python\\Test\\', 15, '<module>', ['print inspect.stack()[0]\n'], 0)
os.path.abspath (inspect.stack()[0][1]) => 'g:\\Python\\Test\\'

The Answer 17

3 people think this answer is useful
import sys
print sys.argv[0]

The Answer 18

2 people think this answer is useful

This should work:

import os,sys

The Answer 19

2 people think this answer is useful

The Answer 20

1 people think this answer is useful

To get directory of executing script

 print os.path.dirname( inspect.getfile(inspect.currentframe()))

The Answer 21

1 people think this answer is useful

I have always just used the os feature of Current Working Directory, or CWD. This is part of the standard library, and is very easy to implement. Here is an example:

    import os
    base_directory = os.getcwd()

The Answer 22

1 people think this answer is useful

Here is what I use so I can throw my code anywhere without issue. __name__ is always defined, but __file__ is only defined when the code is run as a file (e.g. not in IDLE/iPython).

if '__file__' in globals():
    self_name = globals()['__file__']
elif '__file__' in locals():
    self_name = locals()['__file__']
    self_name = __name__

Alternatively, this can be written as:

self_name = globals().get('__file__', locals().get('__file__', __name__))

The Answer 23

0 people think this answer is useful

I used the approach with __file__
but there is a little trick, it returns the .py file when the code is run the first time, next runs give the name of *.pyc file
so I stayed with:

The Answer 24

0 people think this answer is useful

I wrote a function which take into account eclipse debugger and unittest. It return the folder of the first script you launch. You can optionally specify the __file__ var, but the main thing is that you don’t have to share this variable across all your calling hierarchy.

Maybe you can handle others stack particular cases I didn’t see, but for me it’s ok.

import inspect, os
def getRootDirectory(_file_=None):
    Get the directory of the root execution file
    Can help:
    For eclipse user with unittest or debugger, the function search for the correct folder in the stack
    You can pass __file__ (with 4 underscores) if you want the caller directory
    # If we don't have the __file__ :
    if _file_ is None:
        # We get the last :
        rootFile = inspect.stack()[-1][1]
        folder = os.path.abspath(rootFile)
        # If we use unittest :
        if ("/pysrc" in folder) &amp; ("org.python.pydev" in folder):
            previous = None
            # We search from left to right the :
            for el in inspect.stack():
                currentFile = os.path.abspath(el[1])
                if ("unittest/" in currentFile) | ("org.python.pydev" in currentFile):
                previous = currentFile
            folder = previous
        # We return the folder :
        return os.path.dirname(folder)
        # We return the folder according to specified __file__ :
        return os.path.dirname(os.path.realpath(_file_))

The Answer 25

0 people think this answer is useful

To keep the migration consistency across platforms (macOS/Windows/Linux), try:

path = r'%s' % os.getcwd().replace('\\','/')

The Answer 26

0 people think this answer is useful

Simplest way is:


import subprocess['python3',<>])



P.S.: I’ve tried execfile, but since it reads as a string, sys.argv[0] returned <string>.

The Answer 27

-2 people think this answer is useful

Most of these answers were written in Python version 2.x or earlier. In Python 3.x the syntax for the print function has changed to require parentheses, i.e. print().

So, this earlier high score answer from user13993 in Python 2.x:

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

Becomes in Python 3.x:

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

The Answer 28

-3 people think this answer is useful

if you want just the filename without ./ or .py you can try this

filename =
file_name = __file__[2:-3]

file_name will print testscript you can generate whatever you want by changing the index inside []

The Answer 29

-3 people think this answer is useful
import os

import wx

# return the full path of this file

icon = wx.Icon(os.getcwd() + '/img/image.png', wx.BITMAP_TYPE_PNG, 16, 16)

# put the icon on the frame

Add a Comment