【问题标题】:sys.path.insert cannnot import other python filessys.path.insert 无法导入其他 python 文件
【发布时间】:2019-11-23 06:30:18
【问题描述】:

标题所说的。我在路径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: 添加了一些文件和文件夹结构的屏幕截图,以及错误消息

【问题讨论】:

  • 尝试使用没有空格的目录。
  • @ipaleka 这需要更改目录的名称,这是不允许的。但是,即使将tree two 更改为treetwo,并使用import treetwo.sample_tree2,也会引发错误No module named 'treetwo'
  • 抱歉,发现这个条件太晚了。尝试创建 os.path.join 对象而不是字符串,因为这一直是您的问题:看看与上面的路径相比,您的路径在堆栈跟踪中呈现的不同方式。
  • @ipaleka 你能把它们输入答案,这样我就可以运行代码而不会误解你的回复吗?
  • @ipaleka 我用os.path.exists(r'C:\Users\User\Desktop\all python file\5.0.8\treetwo\sample_tree2.py') == True检查绝对路径字符串中是否有错字,结果我是正确的;绝对路径是对的,所以问题不在于路径字符串

标签: python python-3.x import python-import importerror


【解决方案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', '...其他路径']

称为树2

【讨论】:

  • 它有效。在此之前,我尝试了import treetwoimport treetwo.sample_tree2from treetwo import sample_tree2,但不知何故我错过了最明显的一个。我真的是多么愚蠢。非常感谢您的跟进
猜你喜欢
  • 2018-10-13
  • 2021-01-24
  • 1970-01-01
  • 2021-10-04
  • 2022-01-22
相关资源
最近更新 更多