The process of importing a function from a file in Python is similar to importing modules. You have to create two files. Next, insert the definition of the function in one file and call the function from another.
Create a file with a function
Name the new file myfile.py and insert a function.
Create the second file, in the same directory, let’s call it main.py, and import the file and make a function call.
This code will generate the following message.
Another way to import
Let’s import a file and call a function a bit differently. Instead of using import myfile, we use from myfile import *.
Now, you can call a function, without using the file name at the beginning of it.
This way, the program will import all functions inside the file. In our case, there is only one function.
Import file from another location
If the file where you want to call a function is in a different location than the file you want to import, you have to use the SourceFileLoader class.
I have my second file called myfile2.py at this location: D:/myfile2.py.
The modified main.py file looks like this:
The class SourceFileLoader takes a path and loads a module using the load_module function. This module is assigned to the mymodule variable.
After you run the code, you will get this message.
You can also import a file using the util module.
The result is the same as before.