+2 votes
in Programming Languages by (51.1k points)

How can I import a module which is present in a different directory? 


If my module abc.py is present in the folder "programs/modules" and I want to import the module abc in my test program (test.py) which is present in the folder "programs/testprograms", how can I import?

1 Answer

+2 votes
by (157k points)
selected by
Best answer

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.


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


# first n Fibonacci numbers
def fibonacciNumbers(n):
    nums = []
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return nums


import sys
#sys.path.insert(1, '/home/username/Documents/programming/python')
from modules.fibo import *

if __name__ == "__main__":

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]

Related questions

+2 votes
1 answer
+3 votes
1 answer
+3 votes
1 answer