Creating database file one directory above current

丶灬走出姿态 提交于 2021-01-27 13:01:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!