How to import module in different folder?

I have folder structure as follow.



and I want to import when running I added

import sys,os
from B1.C1.D import x

to But error :ModuleNotFoundError is ocurred.

How to solve this error?

>Solution :

Don’t run a script inside a package. Python files inside packages are intended to be imported, not to be run(*)

Instead, move the script into e.g. a scripts directory, then make sure the root directory of your package (A here) is on your PYTHONPATH or in a place that Python can find, and import x in the script like

from A.B1.C1.D import x

The file and directory layout would then be


and you run your script from BASE, with e.g. python scripts/

If you have another module elsewhere in the package, use a relative import. For example, if you have A/B2/C2/, then import x as follows:

from ....B1.C1.D import x

Yes, that’s a horribly amount of leading dots, but that’s what you get for a deeply nested package structure.

Of course, in this case,

from A.B1.C1.D import x

also works in module y, not only in the script. But relative imports show how modules belong to the same package, and can potentially be handy in case you ever rename the package.

Scripts, on the other hand, are not part of the package. They may use the package, they may provide an executable wrapper around the package, but they should not be included in(side) the package.

*) disregard runnable modules here, because that’s clearly not what the question is about.

Leave a Reply