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:
3
Answers
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…)
You can solve this by adding the current directory to the path:
If you want to add other dir to the path you can repeat:
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:
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