How To Copy The Contents Of A Sqlite Database Into A Csv File.

How To Copy The Contents Of A Sqlite Database Into A Csv File.

python sqlite3 csv

CSV files are comma separated value files. They appear in the format below:

“1”, “Ojo”, “Banker”
“2”, “Bazzan”, “Engineer”

They can also be separated by tab, semi-colon et.c. Contents of a SQLite database might be copied into a csv file for different reason:

  • The csv file might serve as an intermediary i.e in order to transfer the contents of a SQLite database into a PostgreSQL db(or any other db). The contents of the SQLite db are first copied in a csv file, then imported into a PostgreSQL db.

  • Since csv files are easily accessible, contents of a SQLite database might be transferred into it in order to perform quick analysis.

Python has a module named csv that allows implementation of basic CRUD(create, read, update and delete) on csv files. There is also a module named sqlite3 that allow operations to be performed on an SQLite database. In this article, csv and sqlite3 modules are used.

For example; if we want to save the contents of a codes.db file into a new.csv file

The Pseudo-code

  • Connect and query the database to get the required data.
  • Open a context manager for the csv file to save the data
  • Turn the csv file object into a csv writer and save the contents from the database.

Python code

import csv
import sqlite3

db = sqlite3.connect(‘codes.db’)
data = db.execute(‘select * from country_code’)

with open(‘new.csv’, ‘w’, newline=’’) as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

NB:- The purpose of the “ newline=’’ ” argument in the open function is to prevent the addition of newline after each row.