问题
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 = sqlite3.connect('../data/test.db')
However; it says 'unable to open database file' which I'm considering as a directory access error. How do I refer to higher directory in Python?
回答1:
You might try this:
conn = sqlite3.connect(os.path.realpath('../data/test.db'))
回答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)
来源:https://stackoverflow.com/questions/36784897/creating-database-file-one-directory-above-current