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

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

    sqlite3.connect will attempt to create a database if it doesn't exist - so the only way to tell if one does exist is to try to open it and catch an IOError. Then to create a blank database, just connect using the sqlite3 module.

    import sqlite3
    
    try:
        open('idonotexist')
        print 'Database already exists!'
    except IOError as e:
        if e.args == 2: # No such file or directory
            blank_db = sqlite3.connect('idontexist')
            print 'Blank database created'
        else: # permission denied or something else?
            print e
    

    Of course, you may still have to do something with os.makedirs depending on if the structure already exists.

提交回复
热议问题