How can I get the absolute path of an imported module?
Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.
import * as file4 from './file4'; An absolute import path is a path that starts from a root, and you need to define a root first. In a typical JavaScript/TypeScript project, a common root is the src directory. For file1.
Absolute import involves full path i.e., from the project's root folder to the desired module. An absolute import state that the resource to be imported using its full path from the project's root folder.
If you change __path__ , you can force the interpreter to look in a different directory for modules belonging to that package. This would allow you to, e.g., load different versions of the same module based on runtime conditions.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With