Python Practice › SQLite Programs › Program 18
Export a table to CSV
Write a Python program to export a table to a CSV file.
Output
name,marks Asha,91 Ravi,74
Approach
- Read rows and column names, then use
csv.writer.
Solution
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.