24

How can I get the absolute path of an imported module?

2
  • Do you mean the file system path to the file, or the Python module path? Commented Sep 2, 2012 at 6:15
  • In case anyone is looking to do this with a function function_name.__code__ works nicely at getting the full file path. Commented Sep 28, 2017 at 19:29

3 Answers 3

44

As the other answers have said, you can use __file__. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this:

>>> import os >>> import math >>> os.path.abspath(math.__file__) '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so' 

Here's an example with a module I made called checkIP to illustrate why you need to get the abspath (checkIP.py is in the current directory):

>>> import os >>> import checkIP >>> os.path.abspath(checkIP.__file__) '/Users/Matthew/Programs/checkIP.py' >>> checkIP.__file__ 'checkIP.py' 
Sign up to request clarification or add additional context in comments.

Comments

9

If it is a module within your PYTHONPATH directory tree (and reachable by placing a __init__.py in its directory and parent directories), then call its path attribute.

>>>import sample_module >>>sample_module.__path__ ['/absolute/path/to/sample/module'] 

Comments

3

You can try:

import os print os.__file__ 

to see where the module is located.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.