File.py包含一个名为function的函数。如何导入?
from file.py import function(a,b)
上面给出了一个错误:
ImportError:没有名为'file.py'的模块;文件不是包
File.py包含一个名为function的函数。如何导入?
from file.py import function(a,b)
上面给出了一个错误:
ImportError:没有名为'file.py'的模块;文件不是包
当前回答
MathMethod.Py内部。
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
内部Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
输出:1200
其他回答
首先,从file.py导入函数:
from file import function
之后,使用以下方法调用函数:
function(a, b)
请注意,file是Python的核心模块之一,所以我建议您将file.py的文件名更改为其他内容。
请注意,如果您试图将函数从a.py导入到名为b.py的文件中,则需要确保a.py和b.py位于同一目录中。
修复
ModuleNotFoundError:没有命名模块
尝试在文件名前使用点(.)来进行相对导入:
from .file import function
以上任何一种方法都不适合我。我得到ModuleNotFoundError:没有模块命名任何错误。 所以我的解决方案是像下面这样导入
from . import filename # without .py
在我的第一个文件中,我定义了如下函数fun
# file name is firstFile.py
def fun():
print('this is fun')
在第二个文件中,假设我想把这个函数命名为fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
解决方案1:在一个文件myfun.py中定义任何函数。
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
在另一个文件中:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
解决方案2:如果上述解决方案对Colab不起作用
创建一个foldermyfun 在这个文件夹中创建一个文件__init__.py 在__init__.py中编写所有函数 从myfun Import *导入Colab笔记本中的函数
首先将文件保存为.py格式(例如my_example.py)。 如果那个文件有函数,
def xyz():
--------
--------
def abc():
--------
--------
在调用函数中,您只需键入下面的行。
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================