Ok, So I have a database called cars.db which has a table == inventory,
Inventory essentially contains
('Ford', 'Hiluz', 2),
('Ford', 'Tek', 6),
('Ford', 'Outlander', 9),
('Honda', 'Dualis', 3),
('Honday', 'Elantre', 4)
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)
First, from the menu choose tool menu item. Second, choose the database and table that you want to import data then click the Next button. Third, choose CSV as the data source type, choose the CSV file in the Input file field, and choose the ,(comma) option as the Field separator as shown in the picture below.
SQLite Python: Querying Data First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.
You should just do:
rows = c.fetchall()
csvWriter.writerows(rows)
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)
import sqlite3
import csv
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "cars.db")
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT rowid, * FROM inventory")
columns = [column[0] for column in c.description]
results = []
for row in c.fetchall():
results.append(dict(zip(columns, row)))
with open("output.csv", "w", newline='') as new_file:
fieldnames = columns
writer = csv.DictWriter(new_file,fieldnames=fieldnames)
writer.writeheader()
for line in results:
writer.writerow(line)
conn.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With