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

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


当前回答

在“运行时”导入一个已知名称的特定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

其他回答

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

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

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

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

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

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

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

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

import helper
helper.display()

输出,

我正在工作,桑达gsv

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

如果函数定义在x.py文件中:

def greet():
    print('Hello! How are you?')

在导入函数的文件中,这样写:

from x import greet

如果您不希望导入文件中的所有函数,这是非常有用的。

我想补充一点,我在其他地方不太清楚;在模块/包中,当从文件中加载时,模块/包名必须以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