'Correct Format for Absolute Path for SQLite Database in Python

I have a small Python application that references a folder on my Raspberry Pi. I'm using a direct link to the .db file, and want to update to use an absolute link. However, my tries have failed and the path isn't correct. How do I format this for the database link to work anywhere it's installed? The code creates a new database.db file if one doesn't exist, but I want to use code that will always work even without the /home/name/code/... location specified. Thanks!

(I read this, and it didn't help me.)

#Connect to database
sqliteConnection = sqlite3.connect('/home/name/code/bot/database.db')
cursor = sqliteConnection.cursor()

I'm trying to do something more like this, but it isn't working:

#Connect to database
dbdir = os.path.direname(__file__)
dbpath = os.path.join(dbdir, "..", "database.db")
sqliteConnection = sqlite3.connect(dbpath)


Solution 1:[1]

@Dillon Davis got me on the right track. I'm not sure if this is the most elegant way to handle this, but it works:

filename = os.path.abspath(__file__)
dbdir = filename.rstrip('filename.py')
dbpath = os.path.join(dbdir, "database.db")
sqliteConnection = sqlite3.connect(dbpath)
cursor = sqliteConnection.cursor()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric