如何在Python中导入文件?我想导入:

文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)


当前回答

我导入的方式是导入文件,并使用它的名字的速记。

import DoStuff.py as DS
DS.main()

不要忘记你的导入文件必须以.py扩展名命名

其他回答

导入.py文件的最佳方法是使用__init__.py。最简单的方法是在你的.py文件所在的目录下创建一个名为__init__.py的空文件。

Mike Grouchy的这篇文章很好地解释了__init__.py及其用于制作、导入和设置python包的用法。

这就是我从python文件调用函数的方式,这对我来说是灵活的,可以调用任何函数。

import os, importlib, sys

def callfunc(myfile, myfunc, *args):
    pathname, filename = os.path.split(myfile)
    sys.path.append(os.path.abspath(pathname))
    modname = os.path.splitext(filename)[0]
    mymod = importlib.import_module(modname)
    result = getattr(mymod, myfunc)(*args)
    return result

result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)

将python文件从一个文件夹导入到另一个文件夹的复杂方法并不多。只需要创建一个__init__.py文件来声明这个文件夹是一个python包,然后转到你想要导入的主机文件

从root。parent。folder。file导入变量,类,等等

我想补充一点,我在其他地方不太清楚;在模块/包中,当从文件中加载时,模块/包名必须以mymodule作为前缀。想象我的模块是这样布局的:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

当从__init__.py加载somefile.py/otherstuff.py时,内容应该如下所示:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc

只是在另一个python文件中导入python文件

假设我有一个help .py python文件,它有一个显示函数,

def display():
    print("I'm working sundar gsv")

在app.py中,你可以使用display函数,

import helper
helper.display()

输出,

我正在工作,桑达gsv

注意:不需要指定.py扩展名。