Use the import statement to import the Python file into another Python file. Splitting code into different files is really important for a large project.
The name used in the import
statement is simply the module’s filename without the .py
extension at the end.
Import Python file in another Python file
Simple example code.
Import a file in the same directory
from {file name} import {function name}
We have 2 file in same directory: my_math.py
and main.py
. In Python, we don’t need to explicitly export something in math.py
, all the functions seem to be exported by default.
import my_math
my_math.add(10, 20)
# OR
from my_math import add
add(100, 200)
Output:
Import another file from the subdirectory
from {directory name}.{file name} import {function name}
Import another file from a different directory
Suppose there is a file at./src/index.py
, and it wants to import ./util/multiple.py
Do comment if you have any doubts or suggestions on this Python 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.