Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - importing .py file in same directory - ModuleNotFoundError: No module named '__main__.char'; '__main__' is not a package

I'm using Python 3.6 on Windows 10. I have 2 .py files in the same directory, char.py, and char_user.py, as follows:

char.py:

# char.py

import cv2

#######################################################################################################################
class Char:

    # constructor #####################################################################################################
    def __init__(self):
        self.contour = None
        self.centerOfMassX = None
        self.centerOfMassY = None
    # end def

# end class

char_user.py:

# char_user.py

import os
import cv2

# I've tried this various ways, see more comments below
from .char import Char

#######################################################################################################################
def main():

    char = Char()

    char.centerOfMassX = 0
    char.centerOfMassY = 0

    print("finished main() without error")
# end main

#######################################################################################################################
if __name__ == "__main__":
    main()

No matter what I try, on the line in char_user.py where I'm attempting to import file char.py, class Char, I get the error:

ModuleNotFoundError: No module named '__main__.char'; '__main__' is not a package

Here are some of the ways I've tried the import statement in char_user.py:

from .char import Char
from . import Char
import Char
import char

I've tried both with and without an empty __init__.py in the same directory.

I've consulted these posts but none have been able to provide a resolution:

How to import the class within the same directory or sub directory?

ModuleNotFoundError: What does it mean __main__ is not a package?

ModuleNotFoundError: No module named '__main__.xxxx'; '__main__' is not a package

This is the 1st time in Python 3 I've attempted to import a script that I wrote in the same directory (done this many times in Python 2 without concern).

Is there a way to do this? What am I missing?

like image 943
cdahms Avatar asked Feb 20 '18 21:02

cdahms


2 Answers

try this: from char import Char

like image 140
Dawit Abate Avatar answered Sep 25 '22 01:09

Dawit Abate


I was able to get this working with from char import Char, because you are trying to import the class Char from script char.

As far as I am aware, the line from .char import Char is only used if both files were part of a python module (with its own __init__.py), which they are not. In that case, .char explicitly references the file char.py inside the same module folder, rather than from importing from some other module installed to PYTHONPATH.

like image 34
peytondmurray Avatar answered Sep 24 '22 01:09

peytondmurray