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

from file.py import function(a,b)

上面给出了一个错误:

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


当前回答

在我的例子中,我将我的文件命名为help .scrap.py,直到我将其更改为help .py,它才能正常工作

其他回答

在我的主脚本detectiverb .py文件中,我需要调用passGen函数,生成密码哈希,该函数在模块\passwordGen.py下

对我来说最快最简单的解决办法是

下面是我的目录结构

所以在detectiveROB.py中,我用下面的语法导入了我的函数

从模块。passwordGen导入passGen

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

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

附加一个点。在文件名前面,如果你想导入这个文件,这个文件在你运行代码的同一个目录下。

例如,我正在运行一个名为a.py的文件,我想导入一个名为addFun的方法,它是用b.py写的,b.py在同一个目录中

from .b import addFun

您应该将该文件置于与您试图导入的Python文件相同的位置。'from file import function'也足够了。

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