如何在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

其他回答

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

import DoStuff.py as DS
DS.main()

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

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

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

如果你想导入的模块不在子目录中,那么尝试以下方法并从最深的公共父目录运行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。

这就是我从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脚本包含在abc.py中

例如,如果你的文件名为abc.py(导入abc) 限制是你的文件应该和你调用的python脚本在同一个位置。

进口美国广播公司

例如,如果你的python文件在Windows文件夹中。Windows文件夹与调用python脚本的位置相同。

从文件夹导入ABC

在情况下abc.py脚本是可用的内部internal_folder,是在文件夹内

导入ABC

正如James上面所回答的,如果你的文件在某个固定的位置

进口操作系统 导入系统 scriptpath = "../Test/MyModule.py" sys.path.append (os.path.abspath (scriptpath)) 进口MyModule里

如果你的python脚本更新了,你不想上传-使用这些语句自动刷新。好处:)

%load_ext autoreload 
%autoreload 2