Export SQLite Query Results to CSV in Python
Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.
Python code
35 linesimport sqlite3
import csv
def export_query_to_csv(db_path, query, csv_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(column_names)
writer.writerows(rows)
conn.close()
print(f"Exported {len(rows)} rows to {csv_path}")
if __name__ == "__main__":
# Create a sample in-memory database and export
conn = sqlite3.connect(':memory:')
conn.execute("CREATE TABLE employees (id INTEGER, name TEXT, department TEXT)")
conn.executemany(
"INSERT INTO employees VALUES (?, ?, ?)",
[(1, 'Alice', 'Engineering'), (2, 'Bob', 'Marketing'), (3, 'Carol', 'Sales')]
)
conn.commit()
conn.close()
export_query_to_csv(
':memory:',
"SELECT * FROM employees WHERE department != 'Sales'",
'employees_export.csv'
)
Output
Exported 2 rows to employees_export.csv
How it works
The sqlite3 module handles the database connection and query execution. cursor.description provides column names from the result metadata. Using csv.writer with newline='' prevents extra blank lines in the CSV file. Encoding is set to UTF-8 for widespread compatibility. The function is reusable for any database path and query.
Common mistakes
- Forgetting `newline=''` in `open()`, which adds blank lines between rows.
- Not closing the connection if an exception occurs—use a context manager.
- Assuming query results always have headers; use `cursor.description` safely.
Variations
- Use `conn.cursor().execute(query)` and `fetchmany(size)` for large datasets to avoid loading all rows into memory.
- Wrap `export_query_to_csv` with a `try/finally` or context manager to guarantee connection closure.
Real-world use cases
- Generating weekly sales reports from a production database to share with stakeholders.
- Backing up a subset of data from a database into a CSV for archival or migration.
- Exporting user lists or audit logs for compliance or offline analysis.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.