0

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

Hélder Lima
  • 87
  • 1
  • 1
  • 7

1 Answers1

1

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()
Klox
  • 931
  • 12
  • 21
  • This works! However only works if the script is being executed from the file's folder. As far as I understood from the other answer suggested by you, the only way around would be to append the path to the file, right? – Hélder Lima Dec 02 '22 at 01:10