How to import a module from outside the current folder?

Viewed 985

I'm trying to import a module from outside its directory in a.py.

The directory looks something like this:

.project
├── folder_1
│   └── a.py
|
├── folder_2
│   ├── __init__.py
│   └── b.py

My code in a.py

#contents of a.py
from ..folder_2 import b.py

But from this, I'm getting this error

ImportError: attempted relative import with no known parent package

I've been searching for a solution for this problem for quite a while but I haven't been able to find anything that helps.

1 Answers

With the following structure:

├── project
├── __init__.py
├── folder_1
│   ├── __init__.py
│   └── a.py
├── folder_2
│   ├── __init__.py
│   └── b.py
└── main.py 

your a.py will not complain when executing main.py:

from project.folder_1 import a

Since project is a package for main.py and folder_1 and folder_2 are subpackages of it, you can use Intra-package References.

If you want to directly execute a.py, you can simply do the following:

import sys

sys.path.append('..')

from folder_2 import b
Related