Skip to content Skip to sidebar Skip to footer

Creating Database File One Directory Above Current

In PHP, To refer to a higher directory I would use '../../test'; How would I do it in Python? In this case, I'm using SQLite to create a database file. import sqlite3 conn = sqlit

Solution 1:

You might try this:

conn = sqlite3.connect(os.path.realpath('../data/test.db'))

Solution 2:

You need to find absolute path to your database file, using os.path.abspath and os.path.dirname. Then pass the absolute path to sqlite3.connect.

First (internal) os.path.dirname will give you current file's directory, second os.path.dirname will give you parent directory of current file's directory.

from os.path import join, dirname, abspath
db_path = join(dirname(dirname(abspath(__file__))), 'data/test.db')
sqlite3.connect(db_path)

Post a Comment for "Creating Database File One Directory Above Current"