本文介绍了使其成为 Pythonic:如果不存在,则创建一个 sqlite3 数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个 Python 脚本,如果它不存在,它会初始化一个空数据库.
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')
os.system('sqlite3 Database/testDB.db ";"')
# rest of the script...
我能否以更 Pythonic 的方式执行此操作,并带有 try-except,或者这种代码是否可以接受?
Can I do this in a more Pythonic fashion, with a try-except, or is this kind of code acceptable?
推荐答案
我认为你可以这样做:
import sqlite3
conn = sqlite3.connect('Database/testDB.db')
这应该连接到您的数据库并在它不存在的情况下创建它.我不确定这是最 Pythonic 的方式,但它确实使用了 sqlite3
模块而不是 sqlite3
命令.
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.
这篇关于使其成为 Pythonic:如果不存在,则创建一个 sqlite3 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!