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笔记本中的函数
其他回答
解决方案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笔记本中的函数
您应该将该文件置于与您试图导入的Python文件相同的位置。'from file import function'也足够了。
只是一个简单的建议, 那些相信自动导入的人在Pycharm中按alt+ enter无法得到帮助。
只需从你想导入的地方更改文件名: 右键单击文件,然后单击refactor-> rename。 您的自动导入选项将开始出现
以上任何一种方法都不适合我。我得到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`
假设你想调用的文件是anotherfile.py,你想调用的方法是method1,那么首先导入文件,然后导入方法
from anotherfile import method1
如果method1是一个类的一部分,那么这个类是class1,那么
from anotherfile import class1
然后创建一个对象class1,假设对象名称为ob1,则
ob1 = class1()
ob1.method1()