Python Practice › SQLite Programs › Program 18

Export a table to CSV

EasySQLite Programs · 18 of 20

Write a Python program to export a table to a CSV file.

Advertisement
Output
name,marks
Asha,91
Ravi,74

Approach

  1. Read rows and column names, then use csv.writer.

Solution

Python
import csvimport sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (name TEXT, marks INTEGER)")conn.executemany("INSERT INTO students VALUES (?, ?)", [("Asha", 91), ("Ravi", 74)])cur = conn.execute("SELECT * FROM students")with open("students.csv", "w", newline="") as f:    writer = csv.writer(f)    writer.writerow([c[0] for c in cur.description])    writer.writerows(cur)print(open("students.csv").read())
Output
name,marks
Asha,91
Ravi,74

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Leave a Comment