I wrote a Python script which initializes an empty database if it doesn\'t exist.
import os
if not os.path.exists(\'Database\'):
os.makedirs(\'Database\')
Making it Pythonic: create a sqlite3 database if it doesn't exist?
The most Pythonic way to do this is to use the context manager:
import sqlite3
# if we error, we rollback automatically, else commit!
with sqlite3.connect('/Temp/testDB.db') as conn:
cursor = conn.cursor()
cursor.execute('SELECT SQLITE_VERSION()')
data = cursor.fetchone()
print('SQLite version:', data)
In a python shell this echoes for me:
SQLite version: (u'3.5.9',)
To ensure you have a tempfile path that works across platforms, use tempfile.gettempdir
:
import tempfile
with sqlite3.connect(tempfile.gettempdir() + '/testDB.db') as conn:
...