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

from file.py import function(a,b)

上面给出了一个错误:

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


当前回答

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

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

其他回答

导入时不要写.py。

让file_a.py包含一些函数:

def f():
  return 1

def g():
  return 2

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

from file_a import f, g

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

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

首先,从file.py导入函数:

from file import function

之后,使用以下方法调用函数:

function(a, b)

请注意,file是Python的核心模块之一,所以我建议您将file.py的文件名更改为其他内容。

请注意,如果您试图将函数从a.py导入到名为b.py的文件中,则需要确保a.py和b.py位于同一目录中。

以上任何一种方法都不适合我。我得到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` 

如果你的文件在不同的包结构中,你想从不同的包中调用它,那么你可以这样调用它:

假设你的python项目中有以下包结构:

在python文件中你有一些函数,比如:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

你想从Example3.py调用不同的函数,那么你可以通过以下方式做到:

在Example3.py - file中定义import语句用于导入所有函数

from com.my.func.DifferentFunction import *

或者定义想要导入的每个函数名

from com.my.func.DifferentFunction import add, sub, mul

然后在Example3.py中调用execute函数:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

输出:

 add :  30

 sub :  10

 mul :  200