Search code examples
pythonimportmodulepython-importimporterror

Unable to import modules from a directory


I have created a file main.py which imports out_handler.py which imports style_generator.py but every time I try to implement it with import I get this error

Traceback (most recent call last):
  File "c:\Users\mayan\Desktop\food data app with soonacular\main.py", line 1, in <module>
    from modules import out_handler
  File "c:\Users\mayan\Desktop\food data app with soonacular\modules\out_handler.py", line 2, in <module>       
    import style_generator
ModuleNotFoundError: No module named 'style_generator'

This is the structure of the file system

enter image description here

This is the code of main.py

from modules import out_handler
d = out_handler.out()
d.Print(text='rohan')

This is the code of out_handler.py


import os
import style_generator
import text_generator

class terminal:
    __data = ''''''
    def get_data() -> str:
        return terminal.__data
    
    def set_data(text: str) -> None:
        terminal.__data = text

    def add_data(text) -> None:
        terminal.__data += text

    def clear() -> None:
        os.system('cls')

class out:
    def Print(self,text,color='',background='',style='',justtify='left',font=''):
        render = ''
        match font:
            case '':
                render = style_generator.Text.out(text,color=color,background=background,style=style)
            case _:
                render = text_generator.styles.style(text,font=font,color=color,background=background,styles=style,justify=justtify)

        terminal.set_data(render)
        print(render)

out().Print(text="Aryan",color='red',style='bright',font='3-d',justtify='right')

This is the code of style_generator.py

from pyfiglet import Figlet
from colorama import Fore, Back, Style, init
from text_generator import Text

class styles:
    init(autoreset=True)

    def style(text,font,color='',background='',styles = 'normal',justify= 'left'):
        f = Figlet(font,justify=justify)
        result = f.renderText(text)
        return Text.add_style(styles) + Text.add_color(color) + Text.add_background(background) + result

i have tried adding __init__.py file to the module directory also tried using the syntax module.file.py but could not resolve the issue. I hope you guys have solution

Expecting to find the solution to my imports problem.


Solution

  • The first import worked:

    from modules import out_handler
    

    And since those modules are in the same folder, you can import style_generator in the same way:

    from modules import style_generator
    

    Or you can do it this way:

    from . import style_generator