我一直有这个问题的代码,我已经写,我不知道为什么。
我的项目结构:
├──code
| ├── Bot_Tracker
| | ├── __init__.py
| | ├── matchhistory.py
| | ├── discordUI.py
| ├── Tests
| | ├── __init__.py
| | └── test_matchhistory.py我在test_matchhistory.py中的导入语句
from Bot_Tracker.matchhistory import compMatchHistory我不明白为什么我老是犯这个错误。
发布于 2022-07-29 08:36:12
这是一个与Python如何计算包存储位置有关的简单问题。如果包不在python路径中,那么python将无法在导入时访问它。
为了解决这个问题,我需要将包目录和父目录添加到系统路径中。
我使用的代码:
from os import path
import sys
if __package__:
parent_dir = path.dirname(__file__)
root_dir = path.dirname(parent_dir)
if parent_dir not in sys.path:
sys.path.append(parent_dir)
if root_dir not in sys.path:
sys.path.append(root_dir)这段代码基本上可以找到存储文件的目录以及该目录的父目录,然后它会检查sys.path中是否存在指向该目录的路径。
https://stackoverflow.com/questions/72825137
复制相似问题