Skip to content
Advertisement

How to import module in different folder?

I have this folder structure:

A
|---- B1
       |---- C1
              |---- D
                    |---- x.py
|---- B2
       |---- C2
              |---- main.py

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 I received a ModuleNotFoundError

How can I solve this error?

Advertisement

Answer

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.

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