[Python] Why module cannot be found even if I use __init__.py?

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I tried to read how import works and use what is suggested, but I still have questions:

    If I cd to project folder and run python ./test/test1.py I get ModuleNotFoundError: No module named 'lib'.

    • If I add print(os.getcwd()) it does print the current directory which is project. So, why it cannot find lib folder?
    • If I cd to project/test, add import sys sys.path.append('..') to the beginning of test1.py and then run python test1.py it works. But, why I cannot run it from one level above?
    • I also tried to add __init__.py to lib and test folders, but I get same error.
    • If I try changing to relative path from .lib.lib1 ... and run the test.py from project folder I get ImportError: attempted relative import with no known parent package error

    What am I doing wrong?

    test1.py

    from lib.lib1 import MyClass


    Project structure

    project
    lib
    lib1.py
    lib2.py
    test
    test1.py # from lib.lib1 import MyClass

    main.py

    Continue reading...

Compartilhe esta Página