本文介绍了在Python中从sqlite3数据库写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,所以我有一个名为cars.db的数据库,其中有一个表==库存,
Ok, So I have a database called cars.db which has a table == inventory,
库存本质上包含
('Ford', 'Hiluz', 2),
('Ford', 'Tek', 6),
('Ford', 'Outlander', 9),
('Honda', 'Dualis', 3),
('Honday', 'Elantre', 4)
然后我写了这个,目的是将其编辑为csv,但是,我似乎无法解决这个问题,在某些情况下,我可以打印一些东西,但它不正确,当我尝试修复该问题时,什么都不会打印.有什么建议可以让我步入正轨吗?
I then wrote this which is meant to edit that to the csv, however, I can't seem to work this out, in some cases I get stuff to print but its not right, and when I try and fix that, nothing prints. Any suggestions to get me on track?
#write table to csv
import sqlite3
import csv
with sqlite3.connect("cars.db") as connection:
csvWriter = csv.writer(open("output.csv", "w"))
c = connection.cursor()
rows = c.fetchall()
for x in rows:
csvWriter.writerows(x)
推荐答案
您应该这样做:
rows = c.fetchall()
csvWriter.writerows(rows)
如果要遍历行的原因是因为您不想在将它们写入文件之前对其进行预处理,请使用writerow
方法:
If the reason you iterate through the rows is because you wan't to preprocess them before writing them to the file, then use the writerow
method:
rows = c.fetchall()
for row in rows:
# do your stuff
csvWriter.writerow(row)
这篇关于在Python中从sqlite3数据库写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!