Home > Net >  Python: Can't import a function from parent directory
Python: Can't import a function from parent directory

Time:04-06

If I have the following directory structure:

Folder1/
└─ Folder2/
──── a.py
──── b.py
└─── test/
────── c.py

a.py

import b

def say_hello():
    print("Hello World")

def main():
    say_hello()

if __name__ == '__main__':
    main()

b.py

def say_bye():
    print('bye!')

c.py

from hello import a

if __name__ == '__main__':
    a.say_hello()

I'm trying to run c.py But I get this error message:

    import b
ModuleNotFoundError: No module named 'b'

what did I do wrong here?

CodePudding user response:

if a and b are in the same directory add before the import:

sys.path.append(os.path.abspath(os.path.dirname(__file__)))

this will add the relative folder to path.

CodePudding user response:

When your in python, you have many Import errors but this is really common, try to do import .b instead of import b.

  • Related