将 json 格式的 sqlite 数据库中的数据写入 python 格式的文本文件
Write data from sqllite data base in json format to text file in python
我有一个名为 art.db 的数据库,它由 5 table 组成
表格:table1、table2、table3、table4 和 table5
我想将所有 tables 数据以 json 格式写入文本文件。我只能写一个 table 数据。
有人可以帮帮我吗
下面是我的代码:
import json
import sqlite3
con = sqlite3.connect('/content/art.db')
cursor = con.cursor()
cursor.execute('''SELECT * FROM table1''')
rows = cursor.fetchall()
rowarray_list = []
for row in rows:
t = (row[0], row[1])
rowarray_list.append(t)
j = json.dumps(rowarray_list)
with open("table1.js", "w") as f:
f.write(j)
import collections
objects_list = []
for row in rows:
d = collections.OrderedDict()
d["artwork_id"] = row[0]
d["department_id"] = row[1]
objects_list.append(d)
j = json.dumps(objects_list)
with open("final_data.txt", "w") as f:
f.write(j)
final_data.txt 应包含 json 格式的所有 5 table 数据。
您的问题缺少可重现的数据,但您可以尝试这样的操作:
import sqlite3
import json
#
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
tables = ['table1', 'table2', 'table3', 'table4', 'table5']
data = {}
con = sqlite3.connect('/content/art.db')
con.row_factory = dict_factory
cursor = con.cursor()
for table in tables:
cursor.execute(f'''SELECT * FROM {table}''')
rows = cursor.fetchall()
data[table] = rows
with open('final_data.json', 'w') as fp:
json.dump(data, fp, indent=4)
我有一个名为 art.db 的数据库,它由 5 table 组成 表格:table1、table2、table3、table4 和 table5
我想将所有 tables 数据以 json 格式写入文本文件。我只能写一个 table 数据。 有人可以帮帮我吗
下面是我的代码:
import json
import sqlite3
con = sqlite3.connect('/content/art.db')
cursor = con.cursor()
cursor.execute('''SELECT * FROM table1''')
rows = cursor.fetchall()
rowarray_list = []
for row in rows:
t = (row[0], row[1])
rowarray_list.append(t)
j = json.dumps(rowarray_list)
with open("table1.js", "w") as f:
f.write(j)
import collections
objects_list = []
for row in rows:
d = collections.OrderedDict()
d["artwork_id"] = row[0]
d["department_id"] = row[1]
objects_list.append(d)
j = json.dumps(objects_list)
with open("final_data.txt", "w") as f:
f.write(j)
final_data.txt 应包含 json 格式的所有 5 table 数据。
您的问题缺少可重现的数据,但您可以尝试这样的操作:
import sqlite3
import json
#
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
tables = ['table1', 'table2', 'table3', 'table4', 'table5']
data = {}
con = sqlite3.connect('/content/art.db')
con.row_factory = dict_factory
cursor = con.cursor()
for table in tables:
cursor.execute(f'''SELECT * FROM {table}''')
rows = cursor.fetchall()
data[table] = rows
with open('final_data.json', 'w') as fp:
json.dump(data, fp, indent=4)