0

I tried different methods shown on multiple sites but couldnt figure out the problem. I need to import "demo1.py" in "demo2.py". Here is my folder hierarchy:

Project:___ __init__.py
         |_ main.py
         |_ Package1:___ __init__.py
         |            |_ demo1.py
         |_ Package2:___ __init__.py
                      |_ demo2.py

When I have this in main.py, it works.

import Package1.demo1
import Package2.demo2

But this doesnt work in demo2.py

import Package1.demo1

Neither does this:

import Project.Package1.demo1

I tried following this tutorial https://www.programiz.com/python-programming/package but Im doing something wrong. Tried renaming "main.py" to something else in case it is causing problems but that doesnt helped either.

Edit: Solution found

from sys import  path 
import os

par_dir = os.path.abspath(os.path.join(os.path.dirname( __file__ ), os.pardir))
path.append(par_dir)
import Package1.demo
miamiamia
  • 25
  • 4
  • 1
    Possible duplicate of [beyond top level package error in relative import](https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import) – Nithin Apr 29 '19 at 07:35
  • Possible duplicate of [How do I get the parent directory in Python?](https://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python) – nerdicsapo Apr 29 '19 at 07:35

1 Answers1

1
from sys import path
path.append("project-path")

Define it inside of demo1 or demo2, it will work. You may check this question.

nerdicsapo
  • 427
  • 5
  • 16