Skip to content

Python import function from another file in different directory

  • by

If you want to import a function from another file in a different directory in Python then use sys.path. It will tell Python where to look by adding search directories.


    import sys.
    # sys.path is a list of absolute path strings.

    sys.path.append('/path/to/application/app/folder')
    ​
    import file

Note: that the path appended to sys.path is an absolute path.

Python import function from another file in a different directory

Simple example code.

import sys

sys.path.append('C:/Users/Rohit/PycharmProjects/pythonProject/test')

import my_math

my_math.add(20, 30)
my_math.add(120, 230)

Output:

Python import function from another file in different directory
import python module using sys.path.append

You can create a path relative to a module by using a module’s __file__ attribute. For example:

myfile = open(os.path.join(
    os.path.dirname(__file__),
    MY_FILE))

Do comment if you have any doubts or suggestions on this Python import file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading