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

文件(例如file.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文件:

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

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

如果你想导入的模块不在子目录中,那么尝试以下方法并从最深的公共父目录运行app.py:

目录结构:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

在app.py中,将客户端的路径追加到sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

可选(如果你加载例如配置)(Inspect似乎是我的用例中最健壮的一个)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

这个解决方案适用于我的cli,以及PyCharm。

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

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

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

from x import greet

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

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

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