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'的模块;文件不是包
当前回答
解决方案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笔记本中的函数
其他回答
你不需要添加file.py。
只要将该文件与要导入的文件放在相同的位置即可。然后导入你的函数:
from file import a, b
在我的例子中,我将我的文件命名为help .scrap.py,直到我将其更改为help .py,它才能正常工作
您也可以从不同的目录调用该函数,以防您不能或不希望在您正在工作的同一目录中拥有该函数。你可以通过两种方式做到这一点(也许还有更多的选择,但这些是对我有效的方法)。
选择1 临时更改工作目录
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
选择2 将函数所在的目录添加到sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
您应该将该文件置于与您试图导入的Python文件相同的位置。'from file import function'也足够了。
.py文件中的函数(当然)可以在不同的目录中)可以简单地导入,只需先写入目录,然后写入没有.py扩展名的文件名:
from directory_name.file_name import function_name
function_name()