File.py包含一个名为function的函数。如何导入?

from file.py import function(a,b)

上面给出了一个错误:

ImportError:没有名为'file.py'的模块;文件不是包


当前回答

方法1。从file.py导入你想要的特定函数:

from file import function

方法2。导入整个文件:

import file as fl

然后,调用file.py中的任何函数,使用:

fl.function(a, b)

其他回答

导入时不要写.py。

让file_a.py包含一些函数:

def f():
  return 1

def g():
  return 2

要将这些函数导入file_z.py,请执行以下操作:

from file_a import f, g

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

修复

ModuleNotFoundError:没有命名模块

尝试在文件名前使用点(.)来进行相对导入:

from .file import function

解决方案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笔记本中的函数

只是一个简单的建议, 那些相信自动导入的人在Pycharm中按alt+ enter无法得到帮助。

只需从你想导入的地方更改文件名: 右键单击文件,然后单击refactor-> rename。 您的自动导入选项将开始出现