How to use module's location inside a function in the module - python

Viewed 46

I have a file that contains all my python functions called my_funcs.py. The folder containing this file is added to my pythonpath so that I can import it from wherever I need to use it.

I want to write a function that can use the location of the file but it will be inside the module itself. For example, if I were to import the module in an ipython session, then I could use

import my_funcs as mf
location = mf.__file__
print(location)
>>> '/path/to/my/Functions/my_funcs.py'

How can I make a variable like that inside one of the functions inside my_funcs.py itself? I need this to be able to access something relative to the location of the folder Functions, (loaded a saved file from '/path/to/my/Functions/Data/saved_file.npy') but as this is a folder I download on different servers through git, the absolute path location changes and needs to be a variable I can calculate/recall rather than hardcode it. It also needs to be a solution that works on both python2.7 and 3.x

1 Answers

You can directly use __file__ in your my_funcs.py file. __file__ is a special name in python (like __name__) so it does not need to be accessed using a module.

Related