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'; file is not a package
How do I fix this problem?
First of all you do not need a
.py
.If you have a file
a.py
and inside you have some functions:And you want to import them in
z.py
you have to writeYou don't have to add
file.py
.Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
Inside MathMethod.Py.
Inside Main.Py
Output:1200
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
or
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
or
or
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
if method1 is part of a class, let the class be class1, then
then create an object of class1, suppose the object name is ob1, then
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1 Temporarily change your working directory
Alternative 2 Add the directory where you have your function to sys.path