Call a function from another file in Python

363    Asked by JamesWILLIAMS in Python , Asked on Mar 16, 2021

Set_up: I have a .py file for each function I need to use in a program.

In this program, I need to call the function from the external files.

I've tried:

from file.py import function(a,b)

But I get the error:

ImportError: No module named 'file.py'; the file is not a package

How do I fix this problem?

Answered by James WILLIAMS

If you want to call python to use a function from another file then there isn't any need to add file.py at the time of importing. You just need to write from the file import function and then call the function using function(a, b)and you are done. Now why not to use file.py is because it may not work, the file is one of Python's core modules, so it is better that you change the name of your file.


And an important note here that if you're trying to import some functions from file a.py to a file called b.py, make sure that a.py and b.py are in the same directory.



Your Answer

Interviews

Parent Categories