1

I have a project structure that looks like:

enter image description here

The file greet.py is given as:

def greet_morning(message):
    print("Hello, {}", message)

def greet_evening(message):
    print("Evening message: {}", message)

and the file msg.py is given as :

import sys
import os
sys.path.append(os.getcwd())


from greet.greet import greet_morning

greet_morning("heyy")

When I try to run msg.py as python message/msg.py, I get an error saying ImportError: No module named greet.greet. I am running this file from the root. Why do I get this error, when I have already added the cwd in the system path?

Amanda
  • 2,013
  • 3
  • 24
  • 57
  • Possible duplicate of [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – developer_hatch Oct 03 '19 at 07:07
  • https://stackoverflow.com/questions/54955891/how-pycharm-imports-differently-than-system-command-prompt-windows/55083046#55083046 – CristiFati Oct 03 '19 at 07:08

3 Answers3

1

I think is

from untitled.greet.greet import greet_morning

if still doesnt work, add:

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

edit

I think you may find all the possible solutions here Importing files from different folder

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • It still gives an error `ImportError: No module named untitled.greet.greet` – Amanda Oct 03 '19 at 07:04
  • After I added `__init__.py` in all directories, it works but with `from greet.greet import greet_morning`. I had to remove `untitled`. Could you help me understand this? – Amanda Oct 03 '19 at 07:09
  • @Amanda , yes, basically you are making visible your parallel modules by adding them into the sys.path – developer_hatch Oct 03 '19 at 07:10
  • Will I need to do this in all the files inside the project? – Amanda Oct 03 '19 at 08:55
1

enter image description hereadd __init__.py inside greet and msg folder__init__.py

Selvaraj S.
  • 124
  • 1
  • 5
0

You have missed the file __init__.py in your module.

Just create an empty file __init__.py in greet folder.

Js doe
  • 26
  • 4
  • ``` import sys import os sys.path.append(os.path.abspath('../greet')) import greet greet.greet_morning("heyy") ``` – Js doe Oct 03 '19 at 07:52