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

前端 未结 4 919
说谎
说谎 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:39

    Create directory path, database file and table

    Here is a recipe to create the directory path, database file and table when necessary. If these already exist, the script will overwrite nothing and simply use what is at hand.

    import os
    import sqlite3
    
    data_path = './really/deep/data/path/'
    filename = 'whatever'
    
    os.makedirs(data_path, exist_ok=True)
    
    db = sqlite3.connect(data_path + filename + '.sqlite3')
    db.execute('CREATE TABLE IF NOT EXISTS TableName (id INTEGER PRIMARY KEY, quantity INTEGER)')
    db.close()
    

提交回复
热议问题