Recipes

Short, copy-ready solutions for common tasks with platformdirs. Each recipe states which platforms it matters on. For the reasoning behind each directory choice, see Choosing a Directory.

Create a Directory Before Writing

platformdirs only computes paths; by default it does not create anything. Either create the parent yourself:

from platformdirs import user_data_path

db_file = user_data_path("SuperApp") / "data.db"
db_file.parent.mkdir(parents=True, exist_ok=True)
db_file.write_bytes(b"...")

or let platformdirs create the directory when you read the property:

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp", ensure_exists=True)
db_file = dirs.user_data_path / "data.db"
db_file.write_bytes(b"...")

or use a place_*_file method, which creates the missing directories with private permissions (0700) even without ensure_exists:

from platformdirs import PlatformDirs

path = PlatformDirs("SuperApp").place_data_file("db/data.db")
path.write_bytes(b"...")

The last option is the safest on shared Unix machines; see Directory Creation and Safety.

Write a Config File With Defaults

import json

from platformdirs import PlatformDirs

DEFAULTS = {"theme": "light", "autosave": True}

dirs = PlatformDirs("SuperApp", "Acme")
config_file = dirs.user_config_path / "config.json"

if config_file.is_file():
    settings = DEFAULTS | json.loads(config_file.read_text(encoding="utf-8"))
else:
    settings = dict(DEFAULTS)
    path = dirs.place_config_file("config.json")
    path.write_text(json.dumps(settings, indent=2), encoding="utf-8")

Layer Site and User Configuration

Let administrators ship defaults in site directories and users override them. The iterators yield the user directory first, so apply them in reverse:

import json

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp")
config = {}
for directory in reversed(list(dirs.iter_config_paths())):
    file = directory / "config.json"
    if file.is_file():
        config.update(json.loads(file.read_text(encoding="utf-8")))

On Linux this reads /etc/xdg/SuperApp/config.json (or each XDG_CONFIG_DIRS entry, last first) and then ~/.config/SuperApp/config.json. See Search-Path Iterators.

Find the Winning Copy of a File

When only the highest-priority file matters, use find_*_file:

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp")
theme = dirs.find_data_file("themes/dark.css")
if theme is None:
    raise SystemExit("theme not installed")

It searches the user data directory first, then every site data directory, and never creates anything.

Migrate Data Between Versions

If you pass version, each release gets its own folder. Copy the previous version's data on first start:

import shutil

from platformdirs import user_data_path

current = user_data_path("SuperApp", version="2.0")
previous = user_data_path("SuperApp", version="1.0")

if not current.exists() and previous.exists():
    shutil.copytree(previous, current)

To find any earlier version, list the siblings of the current folder: current.parent.iterdir(). Remember that on Windows the cache directory puts the version after Cache (...\SuperApp\Cache\2.0) while the log directory puts it before Logs (...\SuperApp\2.0\Logs), so .parent is not the same level for every directory type.

Keep a Cache Under Control

Caches can be deleted at any time, so clear old entries freely:

import time

from platformdirs import user_cache_path

cache_dir = user_cache_path("SuperApp")
max_age = 30 * 86400  # 30 days

if cache_dir.exists():
    now = time.time()
    for item in cache_dir.rglob("*"):
        if item.is_file() and now - item.stat().st_mtime > max_age:
            item.unlink()

Avoid shutil.rmtree(user_cache_path()) without an app name: that is the user's entire cache folder.

Let Users Override a Directory With Your Own Variable

Many tools let users relocate a directory with an application-specific environment variable, falling back to platformdirs. For example:

import os
from pathlib import Path

from platformdirs import user_cache_path


def cache_dir() -> Path:
    if override := os.environ.get("SUPERAPP_CACHE_DIR"):
        return Path(override).expanduser()
    return user_cache_path("SuperApp", appauthor=False)

The platformdirs documentation shows real projects using this pattern: Black (BLACK_CACHE_DIR), virtualenv (VIRTUALENV_OVERRIDE_APP_DATA), Poetry (POETRY_CONFIG_DIR, POETRY_HOME) and tox (TOX_USER_CONFIG_FILE).

Fall Back When a Directory Is Not Writable

Home directories can be read-only (containers, locked-down machines). Fall back to the temporary directory:

import tempfile
from pathlib import Path

from platformdirs import user_data_path

data_dir = user_data_path("SuperApp")
try:
    data_dir.mkdir(parents=True, exist_ok=True)
    (data_dir / "data.json").write_text("{}", encoding="utf-8")
except OSError:
    data_dir = Path(tempfile.gettempdir()) / "SuperApp"
    data_dir.mkdir(parents=True, exist_ok=True)

PermissionError is a subclass of OSError, so one except covers both.

Use a Runtime Directory for Sockets and Locks

import socket

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp")
sock_path = dirs.place_runtime_file("server.sock")

server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(str(sock_path))

On Linux, place_runtime_file uses $XDG_RUNTIME_DIR when it is safe, else /run/user/<uid>, else a private /tmp/runtime-<uid>. A client finds the socket with dirs.find_runtime_file("server.sock"). See The Runtime Directory.

Windows: Choose the Author Folder

from platformdirs import user_data_dir

user_data_dir("SuperApp", "Acme")             # ...\AppData\Local\Acme\SuperApp
user_data_dir("SuperApp", appauthor=False)    # ...\AppData\Local\SuperApp
user_data_dir("SuperApp")                     # ...\AppData\Local\SuperApp\SuperApp

Use an explicit author when you publish several apps under one organization, appauthor=False for a flat layout. On other platforms appauthor is ignored.

Windows: Roaming Settings, Local Caches

On domain networks with roaming profiles, AppData\Roaming follows the user between machines:

from platformdirs import user_cache_path, user_config_path

settings = user_config_path("SuperApp", "Acme", roaming=True)  # synced
cache = user_cache_path("SuperApp", "Acme")                     # always Local

Keep large or machine-specific files out of the roaming profile; user_cache_dir ignores roaming for that reason.

macOS: Separate Data and Config

On macOS, user_data_dir, user_config_dir and user_state_dir are the same folder. Use subfolders to avoid name clashes:

from platformdirs import user_data_path

app_dir = user_data_path("SuperApp")
config_dir = app_dir / "config"
db_dir = app_dir / "databases"

Linux: Run a System Service as Root

A service running as root should usually write to system locations, not /root:

from platformdirs import PlatformDirs

dirs = PlatformDirs("superapp", use_site_for_root=True)
# As root:      dirs.user_data_dir == "/usr/local/share/superapp"
# As any user:  dirs.user_data_dir == "~/.local/share/superapp" (expanded)

See Running as Root for the full mapping.

Linux: Write Site Config Only When Allowed

import os

from platformdirs import site_config_path, user_config_path

site_dir = site_config_path("SuperApp")
if os.access(site_dir.parent, os.W_OK):
    target = site_dir / "defaults.conf"
else:
    target = user_config_path("SuperApp") / "config.conf"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("[defaults]\n", encoding="utf-8")

Test Without Touching Real Directories

def test_writes_config(platformdirs_isolated):
    from platformdirs import PlatformDirs

    path = PlatformDirs("SuperApp").place_config_file("config.json")
    path.write_text("{}", encoding="utf-8")
    assert path == platformdirs_isolated / "user_config" / "SuperApp" / "config.json"

See Testing Helpers.

See Also