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

前端 未结 4 941
说谎
说谎 2021-02-19 07:09

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\')
          


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 07:57

    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:
        ...
    

提交回复
热议问题