Why Your App Should Not Just Save Data to a Text File

Almost every beginner has written a program that saves data to a text or JSON file. It works, and for tiny projects it is fine. So why does every tutorial eventually reach for a database? This post explains the reasons with small, concrete examples.

The file version

Here is a typical first approach to saving notes in Python:

import json

def save(notes):
    with open("notes.json", "w") as f:
        json.dump(notes, f)

def load():
    with open("notes.json") as f:
        return json.load(f)

Load everything, change the list, save everything. Simple and perfectly reasonable for a personal script.

Reason 1: finding things gets slow and fiddly

To find notes containing "exam", you load the whole file and loop through it. With a hundred notes, that is nothing. With a million, it is slow, and you are writing your own search code. A database lets you ask:

SELECT id, body FROM notes WHERE body LIKE '%exam%';

and, with the right index for exact lookups, it can find rows without reading everything.

Reason 2: two people at once

If two people save at the same moment, the second save overwrites the first, and someone's note disappears. Databases are built for many users changing data at the same time, keeping each change safe.

Reason 3: half-finished saves

If your program crashes halfway through writing the file, you may be left with a broken file and no notes at all. Databases use transactions: a change either happens completely or not at all. See a first look at transactions.

Reason 4: rules about your data

A file accepts anything you write to it. A database can enforce rules: every note must have text, every email must be unique, every order must belong to a real customer. The database refuses bad data instead of letting it quietly pile up.

Reason 5: linking data together

Notes belong to users, users belong to groups. In files, you end up copying user names into each note or inventing your own id system. Databases have keys and joins for exactly this.

A fair comparison

NeedText or JSON fileDatabase
A handful of settingsGreat choiceOverkill
Personal script, one userFineFine
Searching lots of dataSlow and manualBuilt in
Several users at onceRiskyDesigned for it
Rules and links between dataYou write them yourselfBuilt in

The gentle middle ground

You do not need to install a server to get these benefits. SQLite stores a whole database in one file and is included with Python. It is a perfect next step from JSON files: same convenience, real database features.

import sqlite3
conn = sqlite3.connect("notes.db")
conn.execute("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)")

Our how-to on connecting a Python script to SQLite takes it from there.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site