How to retrieve a module's path?


I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve a module’s path in python?

Asked By: Cheery



This was trivial.

Each module has a __file__ variable that shows its relative path from where you are right now.

Therefore, getting a directory for the module to notify it is simple as:

Answered By: Cheery
import a_module

Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:

import os
path = os.path.abspath(a_module.__file__)

You can also try:

path = os.path.dirname(a_module.__file__)

To get the module’s directory.

Answered By: orestis
import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
Answered By: vinoth

As the other answers have said, the best way to do this is with __file__ (demonstrated again below). However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own (i.e. as __main__).

For example, say you have two files (both of which are on your PYTHONPATH):

import bar


import os

Running will give the output:

/path1        # "import bar" causes the line "print(os.getcwd())" to run
/path2/ # then "print(__file__)" runs
/path2/ # then the import statement finishes and "print(bar.__file__)" runs

HOWEVER if you try to run on its own, you will get:

/path2                              # "print(os.getcwd())" still works fine
Traceback (most recent call last):  # but __file__ doesn't exist if is running as main
  File "/path2/", line 3, in <module>
NameError: name '__file__' is not defined 

Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.

Answered By: mcstrother

So I spent a fair amount of time trying to do this with py2exe
The problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system’s path.

Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:

import os,sys
if hasattr(sys,'frozen'): # only when running in py2exe this exists
    base = sys.prefix
else: # otherwise this is a regular python script
    base = os.path.dirname(os.path.realpath(__file__))
Answered By: uri

There is inspect module in python.

Official documentation

The inspect module provides several useful functions to help get
information about live objects such as modules, classes, methods,
functions, tracebacks, frame objects, and code objects. For example,
it can help you examine the contents of a class, retrieve the source
code of a method, extract and format the argument list for a function,
or get all the information you need to display a detailed traceback.


>>> import os
>>> import inspect
>>> inspect.getfile(os)
>>> inspect.getfile(inspect)
>>> os.path.dirname(inspect.getfile(inspect))
Answered By: Tomas Tomecek

I will try tackling a few variations on this question as well:

  1. finding the path of the called script
  2. finding the path of the currently executing script
  3. finding the directory of the called script

(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)

Caveats of Using __file__

For a module that you have imported:

import something

will return the absolute path of the module. However, given the folowing script
print '__file__', __file__

Calling it with ‘python’ Will return simply ‘’. If you add a shebang:

print '__file__', __file__

and call it using ./, it will return ‘./’. Calling it from a different directory, (eg put in directory bar), then calling either

python bar/

or adding a shebang and executing the file directly:


will return ‘bar/’ (the relative path).

Finding the directory

Now going from there to get the directory, os.path.dirname(__file__) can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex.

import os
print '__file__ is:', __file__
print 'os.path.dirname(__file__) is:', os.path.dirname(__file__)

will output:

__file__ is:
os.path.dirname(__file__) is: 

In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current file (as opposed to the file of an imported module). To get around this, you can wrap it in a call to abspath:

import os
print 'os.path.abspath(__file__) is:', os.path.abspath(__file__)
print 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__))

which outputs something like:

os.path.abspath(__file__) is: /home/user/bar/
os.path.dirname(os.path.abspath(__file__)) is: /home/user/bar

Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file_import_testing_link pointing to, with the following content:

import os
print 'abspath(__file__)',os.path.abspath(__file__)
print 'realpath(__file__)',os.path.realpath(__file__)

executing will print absolute paths something like:

abspath(__file__) /home/user/file_test_link
realpath(__file__) /home/user/

file_import_testing_link ->

Using inspect

@SummerBreeze mentions using the inspect module.

This seems to work well, and is quite concise, for imported modules:

import os
import inspect
print 'inspect.getfile(os) is:', inspect.getfile(os)

obediently returns the absolute path. For finding the path of the currently executing script:


(thanks @jbochi)


gives the absolute path of currently executing script (thanks @Sadman_Sakib).

Answered By: jpgeek

If the only caveat of using __file__ is when current, relative directory is blank (ie, when running as a script from the same directory where the script is), then a trivial solution is:

import os.path
mydir = os.path.dirname(__file__) or '.'
full  = os.path.abspath(mydir)
print __file__, mydir, full

And the result:

$ python . /home/user/work/teste

The trick is in or '.' after the dirname() call. It sets the dir as ., which means current directory and is a valid directory for any path-related function.

Thus, using abspath() is not truly needed. But if you use it anyway, the trick is not needed: abspath() accepts blank paths and properly interprets it as the current directory.

Answered By: MestreLion
import module
print module.__path__

Packages support one more special attribute, __path__. This is
initialized to be a list containing the name of the directory holding
the package’s before the code in that file is executed.
This variable can be modified; doing so affects future searches for
modules and subpackages contained in the package.

While this feature is not often needed, it can be used to extend the
set of modules found in a package.


Answered By: Lukas Greblikas

If you wish to do this dynamically in a “program” try this code:
My point is, you may not know the exact name of the module to “hardcode” it.
It may be selected from a list or may not be currently running to use __file__.

(I know, it will not work in Python 3)

global modpath
modname = 'os' #This can be any module name on the fly
#Create a file called ""
f.write("import "+modname+"n")
f.write("modpath = "+modname+"n")
#Call the file with execfile()
print modpath
<module 'os' from 'C:Python27libos.pyc'>

I tried to get rid of the “global” issue but found cases where it did not work
I think “execfile()” can be emulated in Python 3
Since this is in a program, it can easily be put in a method or module for reuse.

Answered By: Robin Randall

I don’t get why no one is talking about this, but to me the simplest solution is using imp.find_module(“modulename”) (documentation here):

import imp

It gives a tuple with the path in second position:

(<open file '/usr/lib/python2.7/', mode 'U' at 0x7f44528d7540>,
('.py', 'U', 1))

The advantage of this method over the “inspect” one is that you don’t need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example.


In python3, importlib module should do:

Doc of importlib.util.find_spec:

Return the spec for the specified module.

First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].spec is returned. If that happens to be
set to None, then ValueError is raised. If the module is not in
sys.modules, then sys.meta_path is searched for a suitable spec with the
value of ‘path’ given to the finders. None is returned if no spec could
be found.

If the name is for submodule (contains a dot), the parent module is
automatically imported.

The name and package arguments work the same as importlib.import_module().
In other words, relative module names (with leading dots) work.

Answered By: PlasmaBinturong

From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.


So in above I had to call from module knowing that top_package and are in the same directory. Here’s how I get the path to

import sys
import os
import imp

class ConfigurationException(Exception):

# inside of
def get_maincli_path():
    maincli_path = os.path.abspath(imp.find_module('maincli')[1])
    # top_package = __package__.split('.')[0]
    # mod = sys.modules.get(top_package)
    # modfile = mod.__file__
    # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
    # maincli_path = os.path.join(pkg_in_dir, '')

    if not os.path.exists(maincli_path):
        err_msg = 'This script expects that "" be installed to the '
        'same directory: "{0}"'.format(maincli_path)
        raise ConfigurationException(err_msg)

    return maincli_path

Based on posting by PlasmaBinturong I modified the code.

Answered By: Al Conrad

Command Line Utility

You can tweak it to a command line utility,

python-which <package name>

enter image description here

Create /usr/local/bin/python-which

#!/usr/bin/env python

import importlib
import os
import sys

args = sys.argv[1:]
if len(args) > 0:
    module = importlib.import_module(args[0])
    print os.path.dirname(module.__file__)

Make it executable

sudo chmod +x /usr/local/bin/python-which

I’d like to contribute with one common scenario (in Python 3) and explore a few approaches to it.

The built-in function open() accepts either relative or absolute path as its first argument. The relative path is treated as relative to the current working directory though so it is recommended to pass the absolute path to the file.

Simply said, if you run a script file with the following code, it is not guaranteed that the example.txt file will be created in the same directory where the script file is located:

with open('example.txt', 'w'):

To fix this code we need to get the path to the script and make it absolute. To ensure the path to be absolute we simply use the os.path.realpath() function. To get the path to the script there are several common functions that return various path results:

  • os.getcwd()
  • os.path.realpath('example.txt')
  • sys.argv[0]
  • __file__

Both functions os.getcwd() and os.path.realpath() return path results based on the current working directory. Generally not what we want. The first element of the sys.argv list is the path of the root script (the script you run) regardless of whether you call the list in the root script itself or in any of its modules. It might come handy in some situations. The __file__ variable contains path of the module from which it has been called.

The following code correctly creates a file example.txt in the same directory where the script is located:

filedir = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(filedir, 'example.txt')

with open(filepath, 'w'):
Answered By: Jeyekomon

you can just import your module
then hit its name and you’ll get its full path

>>> import os
>>> os
<module 'os' from 'C:\Users\Hassan Ashraf\AppData\Local\Programs\Python\Python36-32\lib\'>
Answered By: Hassan Ashraf

If you would like to know absolute path from your script you can use Path object:

from pathlib import Path


cwd() method

Return a new path object representing the current directory (as returned by os.getcwd())

resolve() method

Make the path absolute, resolving any symlinks. A new path object is returned:

Answered By: Vlad Bezden

If you want to retrieve the package’s root path from any of its modules, the following works (tested on Python 3.6):

from . import __path__ as ROOT_PATH

The main path can also be referenced by using __file__ instead.

Hope this helps!

Answered By: fr_andres

If you installed it using pip, "pip show" works great (‘Location’)

$ pip show detectron2

Name: detectron2
Version: 0.1
Summary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.
Author: FAIR
Author-email: None
License: UNKNOWN
Location: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages
Requires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore


$ python -m pip show mymodule

(author: wisbucky)

Answered By: Javi

Here is a quick bash script in case it’s useful to anyone. I just want to be able to set an environment variable so that I can pushd to the code.

module=${1:?"I need a module name"}

python << EOI
import $module
import os
print os.path.dirname($module.__file__)

Shell example:

[root@sri-4625-0004 ~]# export LXML=$( lxml)
[root@sri-4625-0004 ~]# echo $LXML
[root@sri-4625-0004 ~]#
Answered By: shrewmouse

When you import a module, yo have access to plenty of information. Check out dir(a_module). As for the path, there is a dunder for that: a_module.__path__. You can also just print the module itself.

>>> import a_module
>>> print(dir(a_module))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> print(a_module.__path__)
>>> print(a_module)
<module 'a_module' from '/.../.../a_module/'>
Answered By: tupui

If you used pip, then you can call pip show, but you must call it using the specific version of python that you are using. For example, these could all give different results:

$ python -m pip show numpy
$ python2.7 -m pip show numpy
$ python3 -m pip show numpy

Location: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python

Don’t simply run $ pip show numpy, because there is no guarantee that it will be the same pip that different python versions are calling.

Answered By: wisbucky

If you want to retrieve the module path without loading it:

import importlib.util


Example output:

Answered By: BaiJiFeiLong

If your import is a site-package (e.g. pandas) I recommend this to get its directory (does not work if import is a module, like e.g. pathlib):

from importlib import resources  # part of core Python
import pandas as pd

package_dir = resources.path(package=pd, resource="").__enter__()

In general importlib.resources can be considered when a task is about accessing paths/resources of a site package.

Answered By: zwithouta

Here im printing cProfile package path:-

import cProfile
import os
path = os.path.abspath(cProfile.__file__)
Answered By: Rakesh Dara
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.