How to Call a Function from a Different Py File
When working with multiple Python files, it's often necessary to import functions from one file into another. However, issues can arise if the imported file's name collides with a built-in Python module, as demonstrated in the example code.
file.py contains a function named function. How do I import it? from file.py import function(a,b)
This code throws an "ImportError: No module named 'file.py'; file is not a package" error because "file" is a core Python module. To resolve this issue, follow these steps:
from file import function
function(a, b)
Ensure that both the exporting and importing files are in the same directory for successful function import.
Alternatively, if you're encountering the same issue with a different file name (e.g., a.py and b.py), place both files in the same directory and use the following code:
import a a.function(a, b)
The above is the detailed content of How to Import and Call a Function from a Separate Python File?. For more information, please follow other related articles on the PHP Chinese website!