Writing to CSV from sqlite3 database in python

So, I have a database called cars.db that has a table == inventory,

Inventory essentially contains

('Ford', 'Hiluz', 2), ('Ford', 'Tek', 6), ('Ford', 'Outlander', 9), ('Honda', 'Dualis', 3), ('Honday', 'Elantre', 4) 

Then I wrote this, which is intended for editing this in csv, however I can’t process it, in some cases I get print material, but it is wrong, and when I try to fix it, it doesn’t print anything. Any suggestions to get me tracking?

 #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) 
+4
source share
1 answer

You should just do:

 rows = c.fetchall() csvWriter.writerows(rows) 

If the reason you are repeating lines is because you do not have to pre-process them before writing them to a file, then use the writerow method:

 rows = c.fetchall() for row in rows: # do your stuff csvWriter.writerow(row) 
+7
source

Source: https://habr.com/ru/post/1502401/


All Articles