如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
当前回答
将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
如果你想导入的模块不在子目录中,那么尝试以下方法并从最深的公共父目录运行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。
from y import *
假设你有一个文件x和y。 你想把y文件导入x。
然后转到您的x文件并放置上述命令。为了测试这一点,只需在y文件中放入一个打印函数,当导入成功时,在x文件中应该打印它。
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”文件只存在于你的当前目录中。
只是在另一个python文件中导入python文件
假设我有一个help .py python文件,它有一个显示函数,
def display():
print("I'm working sundar gsv")
在app.py中,你可以使用display函数,
import helper
helper.display()
输出,
我正在工作,桑达gsv
注意:不需要指定.py扩展名。