Sub topic 4
Helper utilities with dbutils
This chapter assumes you can write basic Python or SQL, know how to create a notebook and attach it to compute, and have seen magic commands such as %sql and %md. It covers dbutils, the built-in helper object in Databricks notebooks. Widgets and notebook-to-notebook calls get their own chapters, so they appear here only briefly.
What dbutils is
dbutils is a Python object that Databricks makes available in every notebook. It gives you helper functions for tasks that are not part of Spark itself: working with files, reading secrets, passing parameters, and calling other notebooks. You do not import it in a notebook. It is also available in Scala and R notebooks, but SQL cells do not have it.
The functions are grouped into modules. The ones you will use most often are:
| Module | Purpose | Example call |
|---|---|---|
| `dbutils.fs` | List, copy, move, and remove files | `dbutils.fs.ls("/Volumes/main/raw/landing")` |
| `dbutils.secrets` | Read secrets without exposing them | `dbutils.secrets.get("my-scope", "api-key")` |
| `dbutils.widgets` | Add notebook parameters | `dbutils.widgets.text("run_date", "2026-01-01")` |
| `dbutils.notebook` | Run or exit notebooks | `dbutils.notebook.exit("done")` |
| `dbutils.library` | Library helpers (limited, see below) | `dbutils.library.restartPython()` |
You can see what is available from inside the notebook. Call dbutils.help() for the list of modules, and dbutils.fs.help() for the commands in one module. Pass a command name to get its signature, for example dbutils.fs.help("cp").
dbutils.help()
dbutils.fs.help("ls")Working with files: dbutils.fs
dbutils.fs operates on paths that the workspace can reach. In Unity Catalog workspaces, the preferred path style is a volume path such as /Volumes/<catalog>/<schema>/<volume>/<file>. Older paths such as dbfs:/ and mounts may still appear in existing code, but check your workspace's policy before building new work on them.
base = "/Volumes/main/raw/landing"
# List a directory. Each entry has path, name, size, and modificationTime.
for f in dbutils.fs.ls(base):
print(f.name, f.size)
# Create a directory, write a small text file, and read the start of it back.
dbutils.fs.mkdirs(f"{base}/tmp")
dbutils.fs.put(f"{base}/tmp/hello.txt", "hello", True)
print(dbutils.fs.head(f"{base}/tmp/hello.txt"))
# Copy, move, and delete.
dbutils.fs.cp(f"{base}/tmp/hello.txt", f"{base}/tmp/hello_copy.txt")
dbutils.fs.mv(f"{base}/tmp/hello_copy.txt", f"{base}/tmp/hello_moved.txt")
dbutils.fs.rm(f"{base}/tmp", True)Points to remember:
puttakes a third argument,overwrite. WithoutTrue, writing to an existing file fails.rmtakes a second argument,recurse. Deleting a non-empty directory withoutTruefails. Deleting withTrueis permanent, so print the path first when it is built from variables.headreturns only the first bytes of a file (65,536 by default). Use Spark to read real data.lsreturnsFileInfoobjects, not strings. Use.pathor.name.- These calls run on the driver node, one operation at a time. They suit housekeeping, not moving thousands of files in a loop.
The %fs magic is shorthand for the same commands, so %fs ls /Volumes/main/raw/landing matches dbutils.fs.ls. In code that will be reviewed and versioned, the Python form is easier to read and to parameterize.
Handling secrets: dbutils.secrets
Credentials such as API keys and database passwords should not appear in notebook cells, because notebooks end up in revision history and in Git. A secret scope stores them, and dbutils.secrets reads them at run time.
dbutils.secrets.listScopes()
dbutils.secrets.list("my-scope")
api_key = dbutils.secrets.get(scope="my-scope", key="api-key")The value returns as a normal string, so your code can use it. Databricks redacts it when you try to print it: the output shows [REDACTED] in place of the value. The redaction only matches the literal value, so it is a safety net and not real protection. Do not log secrets, write them to files, or return them from dbutils.notebook.exit.
Creating scopes and secrets is done outside the notebook, through the CLI, the API, or the workspace UI, and requires the right permissions. If get fails with a "secret does not exist" or permission error, check the scope name, key name, and your access to the scope.
Parameters and notebook control
Two more modules matter for the rest of this tutorial.
dbutils.widgets creates input fields at the top of a notebook. The chapter on widgets covers them in detail. The short version is that a widget has a name, a default, and an optional label, and dbutils.widgets.get returns its value as a string. A job can set the same widget by name.
dbutils.notebook has two main commands:
dbutils.notebook.run(path, timeout_seconds, arguments)starts another notebook as a separate run and returns its exit value.dbutils.notebook.exit(value)stops the current notebook and sets the string that the caller receives.
The exit value is always a string. To return structured data, serialize it, for example with json.dumps, and parse it in the caller. Large results should be written to a table or file, with only the location returned.
import json
# In the child notebook
dbutils.notebook.exit(json.dumps({"status": "ok", "rows": 120}))import json
# In the parent notebook
raw = dbutils.notebook.run("./child_notebook", 60, {"run_date": "2026-01-02"})
result = json.loads(raw)
print(result["rows"])Where dbutils works
dbutils is tied to the notebook environment. This causes most of the confusion people run into.
- Plain Python files. A
.pymodule stored in a Git folder does not getdbutilsas a global name. Importing the module and callingdbutilsinside it raisesNameError. Pass the object in as an argument, or use theWorkspaceClientfrom the Databricks SDK instead. - Executors.
dbutilsworks on the driver. Calling it inside a UDF or amapfunction that runs on workers is not supported. - Local development. Running your code on a laptop with an IDE has no
dbutils. Databricks Connect provides a way to obtain one, but behavior differs from a notebook, so test on the workspace. - Libraries.
dbutils.libraryis limited. Install packages with%pip installat the top of the notebook. After a change that affects loaded packages, calldbutils.library.restartPython()in its own cell, because it clears Python variables.
# A reusable module should not assume dbutils exists.
def read_secret(dbutils, scope, key):
return dbutils.secrets.get(scope=scope, key=key)How dbutils fits the workflow
Each module supports a later step in the notebook life cycle. Secrets keep credentials out of version control. Widgets and notebook.exit let a job pass values into and out of a notebook. File helpers handle landing zones and cleanup. Keeping these calls near the top of a notebook, or inside a thin wrapper, makes the notebook easier to move from interactive work to a scheduled job.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NameError: name 'dbutils' is not defined` | Code runs in a `.py` module or outside a notebook | Pass `dbutils` as an argument or use the Databricks SDK |
| `FileNotFoundException` from `fs.ls` | Wrong path style or missing volume | Check the `/Volumes/...` path and your access |
| Write fails because the file exists | `put` without `overwrite=True` | Pass `True` as the third argument |
| Secret prints as `[REDACTED]` | Normal behavior | Use the value in code and do not print it |
| `dbutils.notebook.run` times out | Child ran longer than the timeout | Raise the timeout or fix the child. A timeout of 0 means no limit |
Exercise
A teammate moves a helper function that calls dbutils.secrets.get from a notebook into a .py file in a Git folder. The function now fails with NameError. Why does it fail, and how would you fix it?
Show answer
dbutils is a global that Databricks provides in notebooks only. A plain Python module imported from a file does not have it. Fix it by passing dbutils (or the secret value itself) into the function as an argument, or by using the Databricks SDK WorkspaceClient inside the module.
Exercise
A child notebook needs to return a status and a row count to its parent. What type can dbutils.notebook.exit return, and how do you send both values?
Show answer
It returns only a string. Serialize both values, for example with json.dumps({"status": "ok", "rows": 120}), call dbutils.notebook.exit with that string, and parse it in the parent with json.loads.