$24.99
Write a function called sqlite_to_csv() that accepts 4 parameters:
filename of a file containing an sqlite database
name of a table
filename of a CSV file
optional number of rows
Your function will read in the contents of the table from the sqlite database, and write them into a CSV file. If the number of rows is specified, only that many rows will be written to the CSV file. If the number of rows is not specified, all rows from the table will be written.
import sqlite3, csv
def sqlite_to_csv( dbname, table, csvname, nrows = -1): connection = sqlite3.connect(dbname) cursor = connection.cursor()
query = ... cursor.execute(query); result = cursor.fetchall() result = list(result)
For full credit try to write the CSV file with column names matching the column names in the database.
Example:
sqlite_to_csv("chinook.db","albums","albums.csv",10)
will create a CSV file called albums.csv with the following contents:
AlbumId,Title,ArtistId
1,For Those About To Rock We Salute You,1
2,Balls to the Wall,2
3,Restless and Wild,2
4,Let There Be Rock,1
5,Big Ones,3
6,Jagged Little Pill,4
7,Facelift,5
8,Warner 25 Anos,6
9,Plays Metallica By Four Cellos,7
10,Audioslave,8
Here is an incomplete Python code you can use for you implementation:
with open(csvname, 'w', newline='') as f: writer = csv.writer(f) header = ... writer.writerow(header) for row in result:
writer.writerow(row)
f.close() connection.close() sqlite_to_csv("chinook.db", "albums", "albums.csv", 10)
Both chinook.db and albums.csv are attached below.