skip to Main Content

I’m trying to import db/connectdb.py in model/task.py, both model and db folder are in the main project folder.

When I try from db.connectdb import ConnectDb I get

ModuleNotFoundError: No module named ‘db’

When I try from ..db.connectdb import ConnectDb I get

ImportError: attempted relative import with no known parent package

Everything works well in PyCharm.

I tried to add __init__.py to each folder but it is giving the same issue.

This is connectdb.py:

import os
import sqlite3


class ConnectDb():
    def __init__(self):
        db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app.db')
        if os.path.isfile(db_path):
            self.db = sqlite3.connect(db_path)
        else:
            #self.db = None
            print("non")

    def get_connection(self):
        return self.db

This is task.py:

#from ..db.connectdb import ConnectDb or
from db.connectdb import ConnectDb
class Tasks():
    def __init__(self):
        self.db = ConnectDb().get_connection()

    def get_all_tasks(self):
        return self.db.execute("Select * from tasks").fetchall()


t = Tasks()
print(t.get_all_tasks())

This is the folder strcture:

enter image description here

3

Answers


  1. When you execute task.py with VS code, it will look for the folder db inside the folder model, and will not find it…You can put the folder db inside the model folder, it should work.(I think there is another method but I don’t know it…)

    Login or Signup to reply.
  2. You can solve this by adding the current directory to the path:

    import os
    import sys
    root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # the line help you to get current file path
    sys.path.append(root) # the line add the file path to path list
    

    If you want to add other dir to the path you can repeat:

    sys.path.append(your_dir)
    

    with your custom directory. But for your project, you only need to add the db folder parrent’s folder to path.

    Final code must be like below:

    import os
    import sys
    root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # the line help you to get current file path
    sys.path.append(root) # the line add the file path to path list
    
    from db.connectdb import ConnectDb
    class Tasks():
    .
    .
    .
    
    Login or Signup to reply.
  3. You could open your settings and search for Execute In File Dir.

    Checking this option will allow you to run the file in the folder where the file is located

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search