Why Python Imports Break When You Add a Second File
Python resolves import names from sys.path and the entry point, not from the folder you happen to be standing in.
Reviewed by Abhijith N M · 24 October 2026 · Editorial standards
You add a second file. One import line later, Python raises `ModuleNotFoundError`, or its less obvious cousin: `ImportError: attempted relative import with no known parent package`. Nothing about the code changed except its position relative to the interpreter's search path. When you write `import abc`, Python checks three places in order. First `sys.modules`, a cache of modules already imported. Then the built-in modules compiled into the interpreter, like `sys`. Then each directory listed in `sys.path`. The first entry of `sys.path` depends on how you launched Python: for `python script.py` it is the directory containing the script, while for `python -m module` it is the current working directory. Those two are not the same, and the difference is the whole trap. Running `python script.py` puts the script's own directory on `sys.path`, so sibling files import fine — but the package itself is never recognized, because Python never sees the parent folder. Relative imports like `from . import helper` need a known parent package, and there isn't one. Run `python -m package.script` instead and Python treats `package` as a package, sets `__package__`, and relative imports resolve. Same files, different entry point, different result. The fix is usually structural: keep absolute imports (`from package import helper`), run modules with `-m` from the project root, and stop relying on the current working directory to make imports work.
Why Python Imports Break When You Add a Second File — Visual Breakdown
# project layout:
# myapp/
# __init__.py
# main.py
# helper.py
# helper.py
def greet(name):
return f"hi {name}"
# main.py — absolute import, run from project root
from myapp.helper import greet
if __name__ == "__main__":
print(greet("sam"))
# from the folder containing myapp/:
# python -m myapp.main works
# python myapp/main.py fails with ModuleNotFoundError:
# the project root is not on sys.path,
# only myapp/ is
# variant: main.py using a relative import
# from .helper import greet
# python -m myapp.main works
# python myapp/main.py raises ImportError: attempted relative import
# with no known parent packageQuick Concept Check
Test your understanding in 15 seconds
Suppose `myapp/main.py` contains `from .helper import greet`, and you run `python myapp/main.py` from the project root, getting `ImportError: attempted relative import with no known parent package`. What is the most direct cause?
Related Concepts
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.