Skip to content

Module 20 · Building Real Python Applications — topic 8 of 13

Data persistence

Keeping application data between runs: choosing between text files, CSV, JSON and SQLite, loading on start-up and saving on change, starting with empty data when nothing is saved yet, and a first look at sqlite3.

Beginner 10 min read·Lesson 301 of 306 in Python Programming

Learning objectives

  • Choose a storage format for an application
  • Load data at start-up and save it on change
  • Store and query data with sqlite3

Definition

Data persistence means storing an application's data outside memory — in files or databases — so it survives after the program ends and can be loaded the next time it starts.

Introduction

An expense tracker that forgets everything when closed isn't useful. Persistence is what turns a script into an application.

Why it matters

Choosing the right storage keeps the application simple now and lets it grow later without rewriting everything.

Detailed explanation

Plain text and CSV files suit simple lists of records and are easy to open in other programs.

JSON suits nested data (records with lists and sub-objects) and maps directly to Python dictionaries and lists.

SQLite (the built-in sqlite3 module) is a full SQL database in a single file: good for larger data, searching and reports.

Load data once at start-up into memory; save after every change, or at clear points such as quitting.

Handle the first run: if the file doesn't exist yet, start with empty data instead of crashing.

Keep storage code in one place (a storage module or repository class) so the format can change without touching the rest of the program.

With sqlite3, always use ? placeholders for values (never string formatting) to avoid SQL injection, and commit changes.

Back up or version important data; storage bugs can destroy it.

Syntax

Python
import sqlite3
con = sqlite3.connect("expenses.db")
con.execute("CREATE TABLE IF NOT EXISTS expenses (id INTEGER PRIMARY KEY, amount REAL, category TEXT)")
con.execute("INSERT INTO expenses (amount, category) VALUES (?, ?)", (250, "food"))
con.commit()
con.close()
  • Files for simple data, SQLite for more.
  • Load on start, save on change.
  • Use ? placeholders.

Code examples

Saving and loading a text file

Python
from pathlib import Path
def save(expenses, path):
Path(path).write_text("".join(f"{a},{c}\n" for a, c in expenses), encoding="utf-8")
def load(path):
p = Path(path)
if not p.exists():
return []
rows = (line.split(",") for line in p.read_text(encoding="utf-8").splitlines())
return [(float(a), c) for a, c in rows]
print(load("data.txt"))
save([(250.0, "food"), (40.0, "travel")], "data.txt")
print(load("data.txt"))
Output
[]
[(250.0, 'food'), (40.0, 'travel')]

A SQLite database

Python
import sqlite3
con = sqlite3.connect("expenses.db")
con.execute("CREATE TABLE IF NOT EXISTS expenses (id INTEGER PRIMARY KEY, amount REAL, category TEXT)")
con.executemany("INSERT INTO expenses (amount, category) VALUES (?, ?)",
[(250, "food"), (40, "travel"), (120, "food")])
con.commit()
print(con.execute("SELECT category, SUM(amount) FROM expenses GROUP BY category ORDER BY category").fetchall())
con.close()
Output
[('food', 370.0), ('travel', 40.0)]

More examples

Proving data survives

Python
import json
import sqlite3
from pathlib import Path
class JsonStore:
def __init__(self, path):
self.path = Path(path)
self.items = json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else []
def add(self, item):
self.items.append(item)
self.path.write_text(json.dumps(self.items, indent=2), encoding="utf-8")
first = JsonStore("store.json")
first.add({"amount": 250, "category": "food"})
first.add({"amount": 40, "category": "travel"})
second = JsonStore("store.json") # a fresh object, as after a restart
print(len(second.items), second.items[-1])
con = sqlite3.connect("app.db")
con.execute("CREATE TABLE t (x)")
con.execute("INSERT INTO t VALUES (1)")
con.commit()
con.close()
con2 = sqlite3.connect("app.db")
print(con2.execute("SELECT COUNT(*) FROM t").fetchone()[0])
con2.close()
Output
2 {'amount': 40, 'category': 'travel'}
1

Step-by-step explanation

  • JsonStore loads existing data in __init__ and saves after every add.
  • Creating a second store from the same file simulates restarting the program; the data is still there.
  • The same is true for SQLite: a new connection sees the committed row.

Expected output

Running “Proving data survives” prints exactly:

TextOutput
2 {'amount': 40, 'category': 'travel'}
1

Practical applications

  • Desktop apps saving settings and documents.
  • Mobile apps and browsers using SQLite internally.

Best practices

  • Keep storage behind one interface.
  • Handle the first run gracefully.
  • Use parameterised SQL and commit.

Common mistakes

Building SQL with f-strings

Avoid

con.execute(f"SELECT * FROM expenses WHERE category = '{category}'")

Prefer

con.execute("SELECT * FROM expenses WHERE category = ?", (category,))

Formatted SQL breaks on quotes and allows SQL injection.

Forgetting to commit

Avoid

con.execute("INSERT ...")
con.close()

Prefer

con.execute("INSERT ...")
con.commit()
con.close()

Uncommitted changes are discarded.

Important notes

  • The next lesson looks at JSON storage in more detail, including versioning and corrupt files.

Key takeaways

  • Persistence keeps data between runs.
  • Text/CSV, JSON or SQLite depending on the data.
  • Load at start, save on change, handle the first run.

Try it yourself

  1. 1
    Store expenses in SQLite and print a total per month.
  2. 2
    Switch the JsonStore example to CSV without changing the code that uses it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhy use ? placeholders in sqlite3 queries instead of f-strings?
Practise this topic