Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

3 matches
Files & data easy

Export List of Dicts to CSV in Python

Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.

csv export dictwriter
Python
import csv

def export_to_csv(data, filename):
    """Export a list of dicts to a CSV file."""
    if not data:
        print("No data to export")
        return
    
    # Get column names from the keys of the first dict
    fieldnames = list(data[0].keys())
    
    with open(filename, 'w', newline='', encoding='utf…
14 0 Open
Files & data easy

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.

sqlite csv export
Python
import 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='', encodi…
17 0 Open
Files & data easy

How to Read Binary File Bytes and Inspect the Header in Python

Read the first bytes of a binary file with pathlib and display them as a hex dump plus an ASCII view to inspect file headers.

binary file-io hex
Python
import pathlib

def inspect_binary_header(filepath: str, num_bytes: int = 16) -> None:
    """Read the first bytes of a binary file and display them as hex and ASCII."""
    path = pathlib.Path(filepath)
    data = path.read_bytes()[:num_bytes]
    
    hex_str = ' '.join(f"{byte:02x}" for byte in data)
    ascii_str …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.