首页 > 解决方案 > VS Code:相对导入 - 没有名为 x 的模块

问题描述

我知道这是关于“没有名为 x 的模块”的另一个问题。但是我已经尝试了从stackoverflow(以及互联网)中找到的所有东西,但它仍然不适合我。

我创建项目的步骤:

  1. 创建一个名为my_projectthen的项目cd my_project
  2. 创建一个虚拟环境python -m venv .env并使用此文件夹打开一个 VS Code 工作区
  3. 这是我的文件夹结构
my_project
├── __init__.py
├── folder_1
│   ├── file_1.py
│   └── folder_2
│       └── file_2.py -- this is where the function my_function is written

但是,file_1.py当我尝试folder_2/file_2.py如下导入函数时

# file_1.py

from folder_1.folder_2.file_2 import my_function

然后我遇到了以下问题:

ModuleNotFoundError: No module named 'folder_1'

希望有人可以提供帮助。

更新: CSBigSur 是正确的。就我而言,这只是Pylance的问题

标签: python

解决方案


尝试这个:

import folder2.file2 as f2
# your code
f2.your_func()

或者

from folder2.file2 import your_func
# your code
your_func()

推荐阅读