'How do i include other files containing function from different directory in Python?
I want to include all files in my_lib as the directory will contains most used function per library. In this case i want to import my_pandas.py.
I already add the library directory my_lib which contains __init__.py and my_pandas.py.
However i cannot run the following command:
from my_lib import my_pandas
How can i run from my_lib import my_pandas command?
Solution 1:[1]
Finding your own custom modules in Python is unfortunately a little fiddly.
You have correctly made my_lib into a module by adding __init__.py. There are two ways to get the module to import correctly, but they boil down to the same thing: the module needs to appear as a subdirectory inside a directory that is in your path.
Therefore your solutions are:
- navigate to
/home/inetvmart/python_appsand run your notebook there instead of inside/home/inetvmart/python_apps/my_lib(the current directory is always included in the path, andmy_libwill be a subdirectory inside your current directory in this case) - add
/home/inetvmart/python_appsrather than/home/inetvmart/python_apps/my_libto your path (then the parent directory will be in the path. Therefore your custom module will be a subdirectory in a directory that is in your path)
In this particular case, then, you can probably just change your second cell to: sys.path.append("/home/inetvmart/python_apps")
I must warn you that this is a somewhat ... hacky ... approach (modifying the path inside a Python script to ensure your imports succeed).
In the medium term, you may like to do something like:
- create a folder called e.g.
/home/<your username>/my_python_modules - put this path into the
$PYTHONPATHenvironment variable (which you could set in your.bashrc/.zshrc/other file)
Then you will be able to import the custom modules inside my_python_modules from anywhere on your machine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paddy Alton |

