如何在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, 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 3.5或更高版本时,可以使用importlib。Util可以直接将.py文件作为模块导入任意位置,而不需要修改sys.path。

import importlib.util
import sys

def load_module(file_name, module_name)
    spec = importlib.util.spec_from_file_location(module_name, file_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

参数file_name必须为字符串或类路径对象。module_name参数是必需的,因为所有加载的Python模块都必须有一个(点)模块名(如sys、importlib或importlib.util),但您可以为这个新模块选择任何可用的名称。

你可以这样使用这个函数:

my_module = load_module("file.py", "mymod")

在使用load_module()函数将该模块导入Python进程一次之后,就可以使用给定的模块名导入该模块。

file.py:

print(f"file.py was imported as {__name__}")

one.py:

print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two

two.py:

print(f"two.py was imported as {__name__})")
import mymod

对于上面的文件,您可以运行以下命令来查看file.py如何变得可导入。

$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod

这个答案基于官方的Python文档:

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

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

在“运行时”导入一个已知名称的特定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的一个非常不为人知的特性是导入zip文件的能力:

library.zip
|-library
|--__init__.py

该包的__init__.py文件包含以下内容:

def dummy():
    print 'Testing things out...'

我们可以编写另一个脚本,它可以从zip归档文件中导入包。只需要将zip文件添加到sys.path。

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()