How to Retrieve a Module's Path in Python
Created
Modified
Using __file__ Attribute
You can retrieve a module's path using the __file__ attribute. For example,
#!/usr/bin/python3
# Import module
import os
print(os.__file__)
/usr/local/lib/python3.10/os.py
However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own.
Using inspect Module
The Path.resolve()
method returns the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.
#!/usr/bin/python3
# Import module
import os
import inspect
print(inspect.getfile(os))
/usr/local/lib/python3.10/os.py