简体   繁体   中英

How do I get sqlite3 to use relative path when connecting to a db?

My flask app is unable to open a db when I use it's relative path:

conn = sqlite3.connect("down.db")

It works fine I use the absolute path:

conn = sqlite3.connect("C:\\Users\\Lenovo\\PycharmProjects\\spacedonline\\down.db")

I've tried using.\ as well. Any help would be appreciated.

Assuming the file is in the same directory as the app, you could do something like

import os

path = os.path.dirname(os.path.realpath(__file__)) # directory path of the app
conn = sqlite3.connect(path+"/down.db")

# or - after @S3DEV comment
conn = sqlite3.connect(os.path.join(path, "down.db"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM