+++
id = "saving-data"
title = "Keeping data between runs"
index = "keeping data between runs (ui.data_folder, files beside the script)"
keywords = ["save", "saving", "persist", "persistence", "remember", "store", "storage", "settings", "preferences", "between runs", "between launches", "json", "database", "sqlite", "app data", "data folder"]
contexts = ["script", "notebook", "window"]
see_also = ["juno.ui.data_folder", "juno.keychain.set_password", "run-contexts", "ui-patterns/saving", "show-files"]
+++
Keep what a program saves in `ui.data_folder(name)`, and keep files the program ships with beside it.

```python
import json
from juno import ui

path = ui.data_folder("Packing List") / "items.json"
items = json.loads(path.read_text()) if path.exists() else []
```

## The app's data folder

`ui.data_folder("Packing List")` returns the folder `App Data/Packing List` in Juno's folder in the Files app, and creates it if it does not exist yet. Every call with the same name, from any copy of the script, returns the same folder, and it sits outside every script's folder, so moving, deleting or restoring a script leaves its data alone. It works in scripts and notebooks, with or without a window.

The name is the folder's name: one nonempty folder name, without `/`, not starting with `.`. Save settings, documents and caches there; for passwords and tokens, use `juno.keychain.set_password`.

## Files the program ships with

Files that come with a script, such as a word list or images, stay beside it. Find them through `__file__`, which a script has and a notebook cell does not: `pathlib.Path(__file__).parent / "words.txt"`.

## Saving safely

Write the new contents to a temporary file in the same folder and move it over the old one with `os.replace`, so an interrupted save never leaves half a file. In a juno.ui window, load in `on_appear` and save in the callbacks that change the data (see ui-patterns/saving).
