Python from the same level directory/folder import reports an error, or reports ModuleNotFoundError: No module named 'network.models'

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
Insert image description here


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 asSources Rootand add the current working folder to Source_Path.
Insert image description here
Then, the original red report from ~ import ~ disappeared. If an import error occurs, a red flag will appear, and the solution is the same.
Insert image description here


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

Guess you like

Origin blog.csdn.net/qq_39691492/article/details/120438627