python - sys.path.insert 无法导入其他 python 文件
问题描述
标题说什么。我在路径中有以下文件结构C:\Users\User\Desktop\all python file\5.0.8
:
5.0.8\
tree one\
little main.py
sample_tree1.py
tree two\
sample_tree2.py
以下是里面的内容little main.py
:
import sys
import sample_tree1
sys.path.insert(0, r'C:\Users\User\Desktop\all python file\5.0.8\tree two\sample_tree2.py')
import sample_tree2
我想导入sample_tree2.py
,但是一运行就会出现错误little main.py
:
Traceback (most recent call last):
File "<ipython-input-1-486a3fafa7f2>", line 1, in <module>
runfile('C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py', wdir='C:/Users/User/Desktop/all python file/5.0.8/tree one')
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py", line 12, in <module>
import sample_tree2
ModuleNotFoundError: No module named 'sample_tree2'
所以发生了什么事?我遵循了这篇文章的最佳答案,以便从另一个路径分支导入文件,但它不起作用。
先感谢您
编辑:
我正在寻找一个解决方案:
1) 不需要改变当前工作目录
2) 不需要更改文件名
3)不需要改变python终端东西的配置
EDIT2:添加了一些文件和文件夹结构的屏幕截图,以及错误消息
解决方案
该sys.path.insert()
命令将路径插入系统路径,并且不应包含文件名。
请使用您的结构在下面尝试:
小main.py:
import sys
import sample_tree1
sys.path.insert(0, r'/my/absolute/path/5.0.8/treetwo')
print(sys.path) # view the path and verify your insert
import sample_tree2
print(sample_tree2.tree2_func())
treetwo 中的 sample_tree2.py
def tree2_func():
return 'called tree2'
输出:
['/my/absolute/path/5.0.8/treetwo', '...其他路径']
称为树2
推荐阅读
- python - webdriver 找不到带有 jscontroller 的显示更多链接
- python - 为什么 asyncio 需要一个特殊的信号处理程序?
- asp.net - 用户名或密码不正确
- sql - SQL Server 2012 消息“CREATE VIEW”必须是查询批处理中的第一条语句
- error-handling - SBCL 绕过调试器并打印错误以在其他环境中显示?
- .net-core - .NET Core 2.2 向 ajax 返回异步 SendGrid 响应
- python - 为什么 rstrip() 不删除尾随空格?
- datatables - 如何修复多个页码并在数据表中搜索?当我单击时,它会保持加载额外的页码和搜索(请参阅下面的详细信息))
- pyspark - 当列名为空白时如何使用 pyspark 过滤器
- algorithm - 像彩虹一样对颜色进行排序的算法