如果db文件不存在,sqlite3.connect()将创建它。我希望它失败。是否有办法这样做?
发布于 2019-09-06 20:53:35
第一种方法是使用os.path.isfile检查文件路径:
import sqlite3
import os
my_path = 'database.db' # or 'absolute_path/to/the/file'
if os.path.isfile(my_path):
    sqlite3.connect(my_path)否则,可以使用uri=True参数指定打开的mode,并在文件丢失时引发错误。如果没有mode,则将创建该文件(如果不存在),因此您可以使用例如rw或ro来避免新文件:
如果文件不存在,这将引发以下错误:
sqlite3.OperationalError:无法打开数据库文件
您可以在文档的以下几章中找到更多关于这些模式的信息:
https://www.sqlite.org/uri.html
https://www.sqlite.org/c3ref/open.html#urifilenamesinsqlite3open
要打开具有特殊字符的文件(对于URI来说是特殊的),另一种方法是使用以下方法:
import pathlib
my_db = pathlib.Path('path/to/data?ba=se.db').as_uri()
sqlite3.connect('{}?mode=rw'.format(my_db), uri=True)
# or sqlite3.connect(f'{my_db}?mode=rw', uri=True)  with f-stringhttps://stackoverflow.com/questions/57828286
复制相似问题