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

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

E.g.

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 (351k 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.

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]

Related questions


...