
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to retrieve Python module path?
In Python, every module exists in a specific file path within the file system. Sometimes, we need to find out where the module is located to perform different operations, like debugging or verifying the version of the module. In this article, we will explore how to retrieve the file path of a module.
Retrieving Path of a Standard Library Module
In this approach, we are going to import the built-in os module, which is part of the Python standard library, and use the 'os.__file__()' to get the absolute path to the actual ".py" or ".pyc" file where the os module is defined.
It indicates to us where Python is loading the module from, making it useful when using multiple Python environments.
Example
Let's look at the following example, where we are going to retrieve the path of the standard library module (os).
import os print(os.__file__)
The output of the above program is as follows -
C:\Python313\Lib\os.py
Retrieving Path of Third-party Module
Here, we are using the request module, which is not built-in, so it is to be installed using the command 'pip install requests'. After the installation, we are importing the request module and using the 'requests.__file__' to indicate where the module is installed.
Example
In the following example, we are going to retrieve the path of the third-party installed module.
import requests print(requests.__file__)
The following is the output of the above program -
C:\Users\Lenovo\AppData\Roaming\Python\Python313\site-packages\requests\__init__.py
Retrieving Path Using inspect.getfile()
In this scenario, we are using the 'inspect.getfile(object)' function from the inspect module used for introspection. Here we are passing the 'json' as an object and retrieving the source file that defines the JSON module.
Example
Consider the following example, where we are going to retrieve the path using the inspect.getfile() function.
import inspect import json print(inspect.getfile(json))
The following is the output of the above program -
C:\Python313\Lib\json\__init__.py