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

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


当前回答

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

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

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

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

import helper
helper.display()

输出,

我正在工作,桑达gsv

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

其他回答

我想补充一点,我在其他地方不太清楚;在模块/包中,当从文件中加载时,模块/包名必须以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文件从一个文件夹导入到另一个文件夹的复杂方法并不多。只需要创建一个__init__.py文件来声明这个文件夹是一个python包,然后转到你想要导入的主机文件

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

导入文件..——参考链接

需要__init__.py文件来使Python将目录视为包含包,这样做是为了防止具有通用名称的目录,如string,在无意中隐藏了模块搜索路径中稍后出现的有效模块。

__init__.py可以只是一个空文件,但它也可以执行包的初始化代码或设置__all__变量。

mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module

这可能听起来很疯狂,但如果您只是为其创建包装器脚本,则可以创建到想要导入的文件的符号链接。

在“运行时”导入一个已知名称的特定Python文件:

import os
import sys

...

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule