Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import module from subfolder – invalid syntax

Here is my Python project folder structure.

project\
    main_code.py
    code\
         __init__.py
         s_utils.py

    data\

in main_code.py I tried:

import os 
os.chdir('absolute path to project folder')
from .code import s_utils

The last line returns error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ImportError: attempted relative import with no known parent package

What is wrong here? According to this post it should work.

>Solution :

When you use a relative import like from .code import s_utils, Python expects that the script (main_code.py) is being executed as part of a package. This means it should be imported as a module, not run directly as a script.

Running main_code.py directly (e.g., python main_code.py), it is treated as the top-level script, not as part of a package. Therefore, relative imports don’t work because there’s no parent package context.

As a solution you could either replace the relative import with an absolute import:

import os
from code import s_utils

or add the project directory to the Python path:

import os
import sys

project_dir = 'absolute path to project folder'
sys.path.append(project_dir)

from code import s_utils
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading