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.

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:

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)
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.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.