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

from file.py import function(a,b)

上面给出了一个错误:

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


当前回答

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

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

下面是我的目录结构

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

从模块。passwordGen导入passGen

其他回答

.py文件中的函数(当然)可以在不同的目录中)可以简单地导入,只需先写入目录,然后写入没有.py扩展名的文件名:

from directory_name.file_name import function_name

function_name()

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

from file import function

方法2。导入整个文件:

import file as fl

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

fl.function(a, b)

你不需要添加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

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

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