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:
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