If you want import 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)
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.