ImportError in terminal for importing a module created in VS Code

Created in VS Code a file containing a new class called Book. When I try and import it via terminal (on MacBook), I get this error message:

ImportError: No module named Book.

This is the VS Code code:

    class Book:

    def __init__(self, title):
        self.title = title

And the terminal:

    from book import Book

What causes this import error, and how do I fix this?


Solution 1:

you may need to add __init__.py file to the folder

The init.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path.

Solution 2:

I have created two files in a directory in the following structure:

.
├── book.py
└── main.py

The file contents are given below:

book.py:

class Book:
    def __init__(self, title):
        self.title = title

main.py:

from book import Book

sample_book = Book("Uncle Tom")
print(sample_book.title)

Then I opened a terminal in the same directory and run the main.py using Python 3.

python3 main.py

Output:

Uncle Tom