Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to import module in different folder?

I have folder structure as follow.

A\B1\C1\D\x.py

A\B2\C2\main.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and I want to import x.py when running main.py. I added

import sys,os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from B1.C1.D import x

to main.py. 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

BASE/scripts/main.py
BASE/A/B1/C1/D/x.py

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


If you have another module elsewhere in the package, use a relative import. For example, if you have A/B2/C2/y.py, 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading