gpt4 book ai didi

python - sys.path.insert 无法导入其他 python 文件

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:20 25 4
gpt4 key购买 nike

标题说的是什么。我在路径 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'

那到底发生了什么?我关注了this post's top answer为了从路径的另一个分支导入文件,但它不起作用。

提前致谢


编辑:

我正在寻找一种解决方案:

1) 不需要改变当前工作目录

2) 不需要更改文件名

3) 不需要改变python终端东西的配置


编辑2:添加了一些文件和文件夹结构的屏幕截图,以及错误消息

path without sample_tree2.py path with sample_tree2.py enter image description here enter image description here enter image description here

最佳答案

sys.path.insert() 命令将路径插入到系统路径中,不应包含文件名。

请尝试以下使用您的结构:

小主.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', '... other paths']

called tree2

关于python - sys.path.insert 无法导入其他 python 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com