Python import from directory/folder at the same level reports an error
Problem Description:
Use Pycharm to open a Python project. There are multiple folders in the project. Open one of the .py files. In the code:
from .py文件的同级目录
import 类/函数/全局变量
is as shown in the figure below. The network and dataset folders are in the same directory as the .py script. You want to import The two functions inside report red
Cause Analysis:
Pycharm will not automatically add the current file directory to Source_Path
solution:
Select the folder where the .py file is located (the picture shows the classification folder), right-click Make Directory as
→ Sources Root
and add the current working folder to Source_Path.
Then, the original red report from ~ import ~ disappeared. If an import error occurs, a red flag will appear, and the solution is the same.
Replenish:
If this problem occurs in a Linux environment, an error will be reported:
ModuleNotFoundError: No module named 'network.models'.
The solution is to add the following code before from network.models import model_selection:
import sys
sys.path.append('../..')
from network.models import model_selection