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 a, b

您也可以从不同的目录调用该函数,以防您不能或不希望在您正在工作的同一目录中拥有该函数。你可以通过两种方式做到这一点(也许还有更多的选择,但这些是对我有效的方法)。

选择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

修复

ModuleNotFoundError:没有命名模块

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

from .file import function

将模块重命名为'file'以外的内容。

当你调用这个函数时,也要确保:

1)如果你导入了整个模块,你在调用它的时候重复模块名:

import module
module.function_name()

or

import pizza
pizza.pizza_function()

2)或者如果你导入特定的函数,带有别名的函数,或者所有使用*的函数,你不需要重复模块名:

from pizza import pizza_function
pizza_function()

or

from pizza import pizza_function as pf
pf()

or

from pizza import *
pizza_function()

首先将文件保存为.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()

============================