如何从子目录中的.py文件导入类?

时间:2020-03-10 09:41:33

标签: python python-3.x

我的文件夹如下:

Folder structure

message.py文件具有我要导入的类Message,类似地,segments.py文件具有我要导入的类Segment

当我这样做时:

from pydifact.message import Message
from pydifact.segments import Segment

我收到以下错误:

Traceback (most recent call last):

  File "<ipython-input-1-cc598c8ad3ca>", line 1, in <module>
    from pydifact.message import Message

ModuleNotFoundError: No module named 'pydifact.message'

但是当我添加时:

import sys
sys.path.insert(0, r"C:\Users\Desktop\automatic-mscons-invoice-generator\edilite\pydifact")

from pydifact.message import Message
from pydifact.segments import Segment

它工作正常。

有没有一种方法可以直接进行导入而无需添加sys.path.insert

我的工作目录是:

C:\Users\Desktop\automatic-mscons-invoice-generator

1 个答案:

答案 0 :(得分:0)

正如您提到的,手动添加到sys.path即可解决问题。

尝试将该路径添加到PYTHONPATH环境变量中,这将告诉解释器import可用的脚本在哪里。

相关问题