Hélder Lima
Hélder Lima

Reputation: 87

How to import a python function from a sibling folder

This question has been asked before. Even though I couldn't get an answer that solves this issue.

I have the following directory and subdirectories:

enter image description here

I have a function hello() in test1.py that I want to import in test2.py.

test1.py:

def hello():
  print("hello")

test2.py:

import demoA.test1 as test1

test1.hello()

Output:

Traceback (most recent call last):
  File "c:/Users/hasli/Documents/Projects/test/demoB/test2.py", line 1, in <module>
    import demoA.test1 as test1
ModuleNotFoundError: No module named 'demoA'

This is exactly as explained in https://www.freecodecamp.org/news/module-not-found-error-in-python-solved/ but I can't access hello()

I am using python 3: Python 3.8.9

Upvotes: 0

Views: 144

Answers (1)

Klox
Klox

Reputation: 966

You need to add demoA to the list of paths used for import.

import sys
sys.path.append('..')

import demoA.test1 as test1

test1.hello()

Upvotes: 1

Related Questions