VS CODE 1.52.1 Python 3.7.9
Path structure
In the past, I could import "MainModule.py" in all of sub-modules in any directory easily like below.
import MainModule
But after I reinstall VS Code, they are unable to find modules in different paths. I've found some solutions importing modules with absolute paths, but there are hundreds sub-modules already making hard to modify them all.
I tried below but nothing works.
In "SubModule_a.py",
import os
os.chdir("C:\\work\\Folder Main")
import MainModule
This still arises ModuleNotFoundError
Modifying "MyWorkspace.code-workspace"
"settings": {
"python.pythonPath": "C:\\anaconda3\\envs\\MyEnv\\python.exe", # for virtual env
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"terminal.integrated.cwd": "C:\\work\\Folder Main" # added this line
}
In short, how can I import "MainModule.py" from "SubModule_A.py" without using absolute path?
To import the module successfully, there're two optional ways:
1.Add the following code in launch.json:
"env": {
"PYTHONPATH":"${workspaceFolder}"
},
"cwd": "${workspaceFolder}"
Then run it through Run without Debugging(Ctrl+F5). It will still throw error if you run by clicking the green triangle button in the upper right corner.

2.Append the current path:
import sys
sys.path.append('./')
from FolderMain import MainModule
When we import a module, python interpreter will search in the current directory, installed built_in modules and third-party modules, the search path is stored in sys.path. ./ represents the current path.

This works both, whatever you run it without debugging or in Terminal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With