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

问题描述 投票:0回答:2

标题说的是什么。我的路径内有以下文件结构

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终端的配置


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

python python-3.x import python-import importerror
2个回答
1
投票

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', '...其他路径']

称为tree2


0
投票

也许使用 GUI 终端重新编译可以实现您尝试做的所有这三件事。或者甚至仅使用我的意见的 Flutter

© www.soinside.com 2019 - 2024. All rights reserved.