yayu yayu - 1 year ago 95
Python Question

Making it Pythonic: create a sqlite3 database if it doesn't exist?

I wrote a Python script which initializes an empty database if it doesn't exist.

import os

if not os.path.exists('Database'):
os.system('sqlite3 Database/testDB.db ";"')

# rest of the script...

Can I do this in a more Pythonic fashion, with a try-except, or is this kind of code acceptable?

Answer Source

I think you can do it like that:

import sqlite3
conn = sqlite3.connect('Database/testDB.db')

This should connect to your database and create it in case that it doesn't exist. I'm not sure this is the most pythonic way, but it does use the sqlite3 module instead of the sqlite3 command.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download