Python import ModuleNotFoundError

I have a Python project that I am working on my local PC using PyCharm, and I execute the code from Google Colab server (because I need the GPU).

I get my project to Colab using GitHub (I upload the package to GitHub and than clone it in Colab).

However, I have problem with imports.

The package structure is like this:

    -> imports and

I try import like that:

import script2
from b.d import script3

This is my test cases:

  • Locally on my PC, the main script is in folder a

  • Remotely on Google Colab, where the main script is the notebook (which is outside of folder a obviously).

In both this cases I get ModuleNotFoundError for my imports.

But if I use relative imports like so:

from . import script2
from ..d import script3

It works great in both of the above cases, but PyCharm complains about relative imports and the script would only execute when the main is outside folder b.

I tried adding to folder d, but to be honest I still don’t fully understand the purpose of this files. And from what I read they are redundant in Python 3.3+ (I use Python 3.7).

So my question is: How can I make the imports work anytime no matter the location of the main script?

Thanks in advance


here it is perfectly explained what is the absolute and relative import of modules and how to work with them. In your case, to do without relative import in the c folder, create the file with the following contents:

import os, sys


Then you will be able to inside leave it

import script2
from b.d import script3

And this import will work outside of the folder with