ImportError: attempted relative import with no known parent package
时间: 2023-10-12 12:11:56 浏览: 64
ImportError: DLL load failed while importing cv2: 找不到指定的模块(亲自解决)
This error occurs when you try to use a relative import in a module that has no known parent package.
For example, let's say you have the following directory structure:
```
my_project/
main.py
utils/
helper.py
```
If you want to import `helper.py` into `main.py`, you might try to use a relative import like this:
```python
from .utils.helper import my_function
```
However, this will result in the `ImportError: attempted relative import with no known parent package` error because `main.py` has no parent package.
To fix this error, you can either:
1. Use an absolute import instead:
```python
from my_project.utils.helper import my_function
```
2. Turn `my_project` into a package by adding an empty `__init__.py` file to the root directory:
```
my_project/
__init__.py
main.py
utils/
helper.py
```
Then you can use the relative import as originally intended:
```python
from .utils.helper import my_function
```
阅读全文