Skip to content
Advertisement

Cannot get an absolute import to work with python 3.7.0

I have a root folder called dumdum which contains an init and a folder called foo. Within foo are an ini and two modules, foo1 and foo6.

JavaScript

I want foo6 to work when called on its own and when a main module in the root folder dumdum calls it, so I have been trying to work out how to get foo6 to work in all cases, i.e. I want foo6 to work on its own and when it is not the main file. I run foo6 from an IDE. Foo6 calls foo1, but when I do that I get an error :

ModuleNotFoundError no folder named ‘foo’

As foo is the parent folder for both foo1 and foo6 I can’t understand why this is happening.

foo1.py:

JavaScript

foo6.py

JavaScript

when I run:

JavaScript

I get:

JavaScript

Traceback

ModuleNotFoundError no module named ‘foo’ in foo6.py…Line 12

Advertisement

Answer

When importing modules without any further path information you need to have the path directly beneath the module location as a member of sys.path. In your case, add C:UserspriperDesktopdumdum to sys.path.

If you start the python program inside the folder dumdumfoofoo6, then os.getcwd() would give you dumdumfoofoo6. Therefore, your import from foo.foo1 import printy, printing_mystr won’t work. Even adding pathlib.Path(__file__).parent is not enough, because this is dumdumfoo and not dumdum as it should be.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement