Saving settings and progress in Pygame

Where to put save files on Windows, macOS and Linux, how to write them so a crash can't corrupt them, and how to load them when they're missing, damaged or from an older version.

2 min readUpdated By Pygame.net editorial team
On this page

Where to save#

Don't save next to your game's files. Once a game is installed or packaged, that folder may be read-only, or may be wiped when the player updates. Each operating system has a per-user place for application data:

SystemFolder
Windows%APPDATA%\YourGame (for example C:\Users\Name\AppData\Roaming\YourGame)
macOS~/Library/Application Support/YourGame
Linux$XDG_DATA_HOME/YourGame, usually ~/.local/share/YourGame

The third-party platformdirs package works these out for you; the example below does it with the standard library.

A complete example#

save_settings.pyDownload
"""Saving settings and progress to the right per-user folder, safely."""
import json
import os
import sys
import tempfile
from pathlib import Path

import pygame

APP_NAME = "MyPygameGame"
DEFAULTS = {"version": 1, "volume": 0.8, "fullscreen": False, "best_score": 0, "unlocked_level": 1}


def data_dir():
    """A writable folder for this game's files on Windows, macOS and Linux."""
    if sys.platform == "win32":
        base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
    elif sys.platform == "darwin":
        base = Path.home() / "Library" / "Application Support"
    else:
        base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
    folder = base / APP_NAME
    folder.mkdir(parents=True, exist_ok=True)
    return folder


SAVE_PATH = data_dir() / "save.json"


def load():
    try:
        data = json.loads(SAVE_PATH.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return dict(DEFAULTS)                          # missing or corrupt: start fresh
    merged = dict(DEFAULTS)
    merged.update({k: v for k, v in data.items() if k in DEFAULTS})   # ignore unknown keys
    return merged


def save(data):
    """Write to a temporary file first, then replace: a crash can't leave a half-written save."""
    fd, tmp = tempfile.mkstemp(dir=SAVE_PATH.parent, suffix=".tmp")
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)
    os.replace(tmp, SAVE_PATH)


pygame.init()
screen = pygame.display.set_mode((640, 300))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 30)
state = load()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                state["volume"] = round(min(1.0, state["volume"] + 0.1), 1)
            elif event.key == pygame.K_DOWN:
                state["volume"] = round(max(0.0, state["volume"] - 0.1), 1)
            elif event.key == pygame.K_SPACE:
                state["best_score"] += 100
            elif event.key == pygame.K_s:
                save(state)
    screen.fill((20, 26, 46))
    lines = [f"Volume {state['volume']:.1f} (Up/Down)", f"Best score {state['best_score']} (Space)",
             "S saves, closing the window saves too", f"File: {SAVE_PATH}"]
    for i, line in enumerate(lines):
        screen.blit(font.render(line, True, (230, 236, 247)), (20, 30 + i * 40))
    pygame.display.flip()
    clock.tick(30)

save(state)
pygame.quit()

Three habits that prevent lost saves#

Write atomically. Writing directly over the old file means a crash or power cut halfway through leaves a broken file and no backup. Writing to a temporary file in the same folder and then calling os.replace() swaps the new file in one step: you always have either the old save or the new one.

Merge with defaults. load() starts from DEFAULTS and copies in known keys from the file. When you add a new setting in an update, old save files still load, and the new setting simply gets its default.

Store a version number. The "version" field lets future code convert old formats: if data["version"] == 1: migrate_to_2(data).

JSON, not pickle#

JSON is readable, portable and safe to load. Python's pickle can store any object, but loading a pickle file can execute code, so a save file shared online could harm a player. Use JSON (or another plain data format) for anything players might exchange.

What to save, and when#

  • Settings (volume, key bindings, fullscreen): save when the player leaves the settings screen.
  • Progress (unlocked levels, best scores): save at checkpoints, level ends and on quit.
  • Mid-level state: only if your game needs it; save positions and values, not Pygame objects (Surfaces and Rects aren't JSON-serialisable; store [x, y, w, h] instead).

Also save when the window closes, but don't rely on that alone: a crash skips it.

In the browser#

Web builds (for example with pygbag) don't have a normal file system. Saves go into browser storage, which the player can clear. Treat web saves as convenient, not permanent.

↑ ↓ to moveEnter to openEsc to close