Reference library

Files & data

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

3 matches
Files & data medium

How to Load Pickle Files Safely in Python

This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.

pickle security serialization
Python
import pickle

# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
    def __reduce__(self):
        return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))

# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())

# Safe ap…
14 0 Open
Files & data medium

How to Write a List of Lines to a Text File Safely in Python

This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.

files atomic-write pathlib
Python
from pathlib import Path
import tempfile
import os

def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
    """Write lines to a text file atomically to avoid corruption."""
    path = Path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    fd, temp_path = tempfile.mkstemp(dir=str…
13 0 Open
Files & data easy

Parameterize SQL queries in Python to prevent SQL injection

Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.

sqlite3 sql injection parameterized query
Python
import sqlite3

def get_users_by_name(name):
    """Fetch users safely using parameterized query."""
    conn = sqlite3.connect(':memory:')
    cursor = conn.cursor()
    
    # Create sample table and data
    cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
    cursor.executemany('INSERT INTO users (name…
15 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.