The PlatformDirs Class

platformdirs.PlatformDirs is the class behind every module function. It holds one set of settings (app name, author, version and flags) and exposes all 27 directories as properties, plus search-path iterators and helpers to place and find files. This page documents the constructor, every property and method, and the platform-specific classes it stands for.

Constructor

PlatformDirs(
    appname=None,
    appauthor=None,
    version=None,
    roaming=False,
    multipath=False,
    opinion=True,
    ensure_exists=False,
    use_site_for_root=False,
)

All parameters can be passed positionally in this order (the order inherited from appdirs) or by keyword. Each one is described in Parameters. AppDirs is an alias of the same class.

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp", "Acme", version="2.0", ensure_exists=True)
print(dirs.user_config_path)

Attributes

Every constructor parameter is stored as an attribute of the same name and can be changed after construction. Properties are computed on every access, so a change takes effect immediately:

dirs = PlatformDirs("SuperApp")
dirs.version = "2.0"
dirs.user_data_dir  # now ends in SuperApp/2.0 (SuperApp\SuperApp\2.0 on Windows)

appname, appauthor and version are validated whenever they are set, in the constructor or later. A value that would escape the base directory raises ValueError:

PlatformDirs("../evil")
# ValueError: appname must stay inside the base directory, got '../evil'

Rejected values are those with a drive (C:x), a leading / or \, or a .. component. Empty values and None are accepted, and False is accepted for appauthor.

Directory Properties

Each directory has a *_dir property returning str and a *_path property returning pathlib.Path. The properties are:

Group Properties
User app directories user_data, user_config, user_cache, user_state, user_log, user_runtime, user_preference
Site app directories site_data, site_config, site_cache, site_state, site_log, site_runtime
Media directories user_documents, user_downloads, user_pictures, user_videos, user_music, user_desktop, user_projects, user_publicshare, user_templates, user_fonts
Executables and applications user_bin, site_bin, user_applications, site_applications

(Append _dir or _path to each name.) Their values on each platform are listed in the Path Reference Table, and Choosing a Directory explains which one to use for what.

With ensure_exists=True, reading a property creates the directory, including missing parents, every time it is read. Fonts, bin, applications and default media directories are never created. See Directory Creation and Safety.

Site Directories With multipath

site_data_dir, site_config_dir, site_applications_dir (Linux and macOS) and site_cache_dir (macOS with Homebrew) are backed by a list of directories. With multipath=False the _dir property returns only the first entry; with multipath=True it returns all entries joined with os.pathsep (: on POSIX):

dirs = PlatformDirs("SuperApp", multipath=True)
dirs.site_data_dir
# '/usr/local/share/SuperApp:/usr/share/SuperApp' on Linux with no XDG_DATA_DIRS
dirs.site_data_path
# PosixPath('/usr/local/share/SuperApp'), the first entry only

The _path variants always return the first entry, whatever multipath says. Under multipath, if an entry would itself contain os.pathsep (because appname or version contains :), the _dir property raises ValueError: multipath cannot join site directories that contain ':', got [...] instead of returning an ambiguous string. site_applications_dir does not use the app name, so it never raises this.

To work with the individual entries, prefer the iterators over splitting the string.

Search-Path Iterators

Configuration and data are often layered: system-wide defaults in site directories, user overrides in the user directory. The iterators yield those directories in priority order, user directory first, then every site directory:

Method Yields (str) Path twin
iter_config_dirs() user_config_dir, then each site config entry iter_config_paths()
iter_data_dirs() user_data_dir, then each site data entry iter_data_paths()
iter_cache_dirs() user_cache_dir, then each site cache entry iter_cache_paths()
iter_state_dirs() user_state_dir, then site_state_dir iter_state_paths()
iter_log_dirs() user_log_dir, then site_log_dir iter_log_paths()
iter_runtime_dirs() user_runtime_dir, then site_runtime_dir iter_runtime_paths()

Behavior worth knowing:

  • All site entries, regardless of multipath. On Linux, iter_data_dirs() yields ~/.local/share/SuperApp, /usr/local/share/SuperApp and /usr/share/SuperApp (or one entry per XDG_DATA_DIRS element) even with multipath=False.
  • Duplicates are dropped. Directories are compared as Path objects, so on platforms where site and user directories coincide (Android, iOS, site_runtime_dir on macOS and Windows) each one appears once.
  • Lazy. Directories are produced one at a time. With ensure_exists=True, each one is created as it is yielded, so stopping after the first item creates only that directory.
  • Root redirect. On Unix, when running as root with use_site_for_root=True, the user directory is skipped (it already is the site directory). For runtime directories the site entry is skipped instead.

Example: merge config files so the user's settings win over site defaults:

import json

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp")
config = {}
# Iterate site directories first, so the user directory is applied last and wins.
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")))

Placing Files

place_config_file(name), place_data_file(name), place_cache_file(name), place_state_file(name), place_log_file(name) and place_runtime_file(name) return the path where a file should be written in the matching user directory, after creating the missing directories:

from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp")
path = dirs.place_config_file("profiles/default.toml")
path.write_text('theme = "dark"\n', encoding="utf-8")
  • name is a path relative to the user directory and may contain subfolders.
  • The method creates the user directory and every missing parent of the file, with mode 0700 (subject to the umask), whether or not ensure_exists is set. Existing directories keep their mode. The file itself is not created; you write it.
  • It returns a Path. Under multipath it still uses the single user_*_path.
  • On Unix as root with use_site_for_root=True, the file goes under the site directory instead, new directories get mode 0755, and every path component must be owned by root.

Errors:

Situation Exception
name is empty or "." ValueError: name must point to a file, got ''
name is absolute, has a drive, or contains .. ValueError: name must stay inside the base directory, got '...'
The home directory is unknown, so the path still starts with ~ RuntimeError: could not determine the home directory, refusing to create '~/...'
An unsafe existing component on Unix (see Directory Creation and Safety) PermissionError
A missing drive or network share OSError

place_runtime_file additionally raises PermissionError on Unix if the temporary runtime fallback belongs to another user.

Finding Files

find_config_file(name) returns the first existing regular file named name in iter_config_paths() order, or None. find_config_files(name) returns every match as a list, user directory first. The same pairs exist for data, cache, state, log and runtime:

First match All matches
find_config_file(name) find_config_files(name)
find_data_file(name) find_data_files(name)
find_cache_file(name) find_cache_files(name)
find_state_file(name) find_state_files(name)
find_log_file(name) find_log_files(name)
find_runtime_file(name) find_runtime_files(name)
from platformdirs import PlatformDirs

dirs = PlatformDirs("SuperApp", "Acme")
if (config_file := dirs.find_config_file("config.toml")) is not None:
    print(config_file.read_text(encoding="utf-8"))

for plugin_file in dirs.find_config_files("plugins/enabled.toml"):
    print(plugin_file)
  • Only regular files match: a directory named config.toml is skipped, and so is a directory you are not allowed to search.
  • They never create anything, even with ensure_exists=True.
  • name may contain subfolders; an absolute path, a drive or a .. component raises ValueError.
  • On Unix and macOS, find_runtime_file skips an XDG_RUNTIME_DIR that fails the safety checks rather than searching it.
  • A subclass that overrides an iter_*_paths method changes where the matching find_* methods search.

Platform Classes

PlatformDirs is chosen once, when platformdirs is imported:

Platform Class
Android app (see detection) platformdirs.android.Android
sys.platform == "win32" platformdirs.windows.Windows
sys.platform == "darwin" platformdirs.macos.MacOS
sys.platform == "ios" platformdirs.ios.IOS
anything else (Linux, BSD, Cygwin, ...) platformdirs.unix.Unix

All of them inherit from the abstract base class platformdirs.api.PlatformDirsABC (also exported as platformdirs.PlatformDirsABC), which defines the constructor, the *_path properties, the iterators and the place_*/find_* methods. A platform class implements the 27 abstract *_dir properties.

You can import a specific class to see what it would return, but the classes call platform APIs (the Windows Shell API, os.geteuid on Unix), so results on a foreign platform are not meaningful. To type-annotate a variable that holds any of them, use PlatformDirsABC:

from platformdirs import PlatformDirs, PlatformDirsABC

def configure(dirs: PlatformDirsABC) -> None:
    ...

configure(PlatformDirs("SuperApp"))

RuntimeDirWarning

platformdirs.RuntimeDirWarning is a UserWarning subclass emitted when user_runtime_dir on Unix or macOS cannot use XDG_RUNTIME_DIR and falls back to another location. Each distinct message is emitted once per process. See Linux and Unix for how to silence it.

See Also