Call Python function from a different directory’s Python file

Hello friends, in this tutorial we are going to learn how to call a function from a different directory’s Python file. In Python, you can use the functions of other Python files by using the import keyword.

Call function from a different directory’s Python file

In order to call a function from a different directory you need to add it to your system’s path. In my code, I have imported the sys module, which enabled me to add the directory in question to the path. I have made a file named my_modules and created two functions to it, add and sub. add() returns the sum of the two numbers whereas the sub() function returns the difference between the two numbers. I have created a new folder called my_newFolder. In this folder, I have made another Python file with the name, import_myModule.

my_modules.py

def add(a, b):
    return (a + b)

def sub(a, b):
    return (a - b)

import_myModules.py

import sys

sys.path.append("my_newFolder")

import my_modules 

print(my_modules.add(9, 6))

Using the sys module function path() and append() I have appended the name of the new folder to my system’s path. After appending the folder’s name to my path, I can import the functions to my code. As you can see, I have imported my entire file i.e. my_modules and then used the add() function by passing 9 and 6 as arguments.

Output : 

15

Now you know how you can import functions from different files which are not part of the same directory.

You can also learn how to call a function from the same directory from my earlier post on Call Python function from another Python file.

Leave a Reply

Your email address will not be published. Required fields are marked *