我有1000条记录,我希望以100条为循环循环并写入多个文件。下面的代码在所有文件中创建相同的数据集。
conn = cx_Oracle.connect('username/password@db')
curs = conn.cursor()
curs.execute('SELECT * FROM TABLE ORDER BY CREATION_TIME')
result = curs.fetchmany(100)
items = [dict(zip([key[0] for key in curs.description], row)) for row in result]
for i in range(10):
with open('C:\\Users\\Output%i.json' % i, 'w') as outfile:
json.dump({'items': items}, outfile, sort_keys=True, indent=1, ensure_ascii=False, default=default)
答案 0 :(得分:0)
您需要循环调用curs.fetchmany()
,而不是在获取100行之后放置循环。
i = 0
while True:
result = curs.fetchmany(100)
if len(result) == 0:
break:
items = [dict(zip([key[0] for key in curs.description], row)) for row in result]
with open('C:\\Users\\Output%i.json' % i, 'w') as outfile:
json.dump({'items': items}, outfile, sort_keys=True, indent=1, ensure_ascii=False, default=default)
i += 1