设置_up。我为我需要在程序中使用的每个函数准备了一个.py文件。
在这个程序中,我需要从外部文件中调用这个函数。
我已经试过了。
from file.py import function(a,b)
但我得到的是错误。
ImportError:没有名为'file.py'的模块;文件不是一个包。
我怎样才能解决这个问题?
在导入的时候不需要添加file.py
。只要写上from file import function
,然后用function(a, b)
调用该函数。这可能行不通,原因是file
是Python的核心模块之一,所以我建议你改变你的文件名。
注意,如果你想从a.py
导入函数到一个叫b.py
的文件,你需要确保a.py
和b.py
在同一个目录下。
首先,你不需要一个.py
。
如果你有一个文件a.py
,里面有一些函数。
def b():
# Something
return 1
def c():
# Something
return 2
而你想在z.py
中导入它们,你必须写上
from a import b, c
你可以通过两种方式来实现。 首先,从file.py中导入你想要的特定函数。 要做到这一点,可以使用
from file import function
另一种方法是导入整个文件
import file as fl
然后你就可以在file.py中使用
fl.function(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
如果你的文件在不同的包结构中,你想从不同的包中调用它,那么你可以用这种方式调用它。
比方说,在你的python项目中,你有如下的包结构。
[![Python包和文件结构][1]][1]
[1]: https://i.stack.imgur.com/lZONx.png
在-com.my.func.DifferentFunction
的python文件中,你有一些函数,比如:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
。
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
中定义导入语句--导入所有函数的文件。
from com.my.func.DifferentFunction import *
或定义每个你想导入的函数名称。
from com.my.func.DifferentFunction import add, sub, mul
然后在Example3.py
中调用函数执行。
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
首先将文件保存为.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()
============================
将模块改名为除'文件'以外的其他内容。
然后在调用函数的时候也要确定。
1)如果你要导入整个模块,在调用时要重申模块名称。
import module
module.function_name()
或
import pizza
pizza.pizza_function()
2)或者如果你导入的是特定的函数,带有别名的函数,或者所有函数都使用*,你就不要重申模块名了。
from pizza import pizza_function
pizza_function()
或
from pizza import pizza_function as pf
pf()
或
from pizza import *
pizza_function()