如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
当前回答
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
以下是我现在已经理解的两种简单方法,确保你想导入的“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
如果你想导入的模块不在子目录中,那么尝试以下方法并从最深的公共父目录运行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
如果您不希望导入文件中的所有函数,这是非常有用的。
将python文件从一个文件夹导入到另一个文件夹的复杂方法并不多。只需要创建一个__init__.py文件来声明这个文件夹是一个python包,然后转到你想要导入的主机文件
从root。parent。folder。file导入变量,类,等等
这可能听起来很疯狂,但如果您只是为其创建包装器脚本,则可以创建到想要导入的文件的符号链接。