You can insert/append the path to your module that you want to import to sys.path. You need to make sure that your module name is not some system filename to avoid any unwanted error.
E.g.
I have fibo.py in the folder: ~/Documents/programming/python/modules
and I want to import fibo in my test program (test.py) which is present in the folder: ~/Documents/programming/python/algos
fibo.py
# first n Fibonacci numbers
def fibonacciNumbers(n):
nums = []
a, b = 0, 1
for i in range(n):
nums.append(a)
a, b = b, a + b
return nums
test.py
import sys
sys.path.append('/home/username/Documents/programming/python')
#sys.path.insert(1, '/home/username/Documents/programming/python')
from modules.fibo import *
if __name__ == "__main__":
print(fibonacciNumbers(10))
You need to use the absolute path to insert/append to sys.path; the relative path will not work.
If you run test.py using python3, it will give the following output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]