Skip to content

11. Recipes ​

Step-by-step recipes for working with many entries at once. Each recipe is safe if you follow three rules:

  1. Run with DRY_RUN = True first and check the printed plan. When it looks right, set it to False.
  2. Write it so that re-running gives the same result (do not create what already exists, do not re-upload identical files). If it stops halfway, just run it again.
  3. Try it on a test team / category first.

The examples assume a client like this:

python
import elabftw_toolkit

elab = elabftw_toolkit.client("your-team-name")

Bulk-creating Resource items from CSV / Excel ​

Assumes one row of samples.csv per item, a title column for the title, and other column names equal to eLabFTW field names.

text
title,purity,form,lot_number
SAMPLE-001,99.9%,powder,L001
SAMPLE-002,99.5%,plate,L002
python
import pandas as pd
import elabftw_toolkit

elab = elabftw_toolkit.client("your-team-name")
DRY_RUN = True
CATEGORY = "Sample"

df = pd.read_csv("samples.csv", dtype=str).fillna("")
# For Excel: df = pd.read_excel("samples.xlsx", dtype=str).fillna("")   # needs openpyxl

category_id = elab.items.categories.id(CATEGORY)
existing = {x["title"] for x in elab.items.all(category_title=CATEGORY)}   # fetch the list only once

for row in df.to_dict("records"):
    title = row.pop("title")
    if title in existing:
        print("skip (exists):", title)
        continue
    if DRY_RUN:
        print("would create:", title, row)
        continue
    new_id = elab.items.init(title=title, category_id=category_id, template_name=CATEGORY)
    elab.items.entry(new_id).fields.update(row)    # column name = field name
    existing.add(title)
    print("created:", new_id, title)
  • By default fields.update() rejects field names that are not in the template (ValueError), so typos in column names are caught.
  • Building the set of titles once with all() is much faster than calling find() for each row.
  • Experiments work the same way with elab.experiments.init(...) (use fail_if_title_exists_in_category=True to prevent duplicates).

Safely updating a field across many entries (with a dry run) ​

Example: in the category "Sample", change form from pwd to powder.

python
import json
from pathlib import Path
import elabftw_toolkit

elab = elabftw_toolkit.client("your-team-name")
DRY_RUN = True

entries = elab.items.all(full=True, category_title="Sample", cache_dir="cache")
targets = [x for x in entries if elabftw_toolkit.extra_fields(x).get("form") == "pwd"]
print(len(targets), "entries to change")

# Save the metadata before the change (for rolling back)
Path("backup").mkdir(exist_ok=True)
for x in targets:
    Path(f"backup/item_{x['id']}.json").write_text(
        json.dumps(elabftw_toolkit.metadata_of(x), ensure_ascii=False, indent=2), encoding="utf-8")

for x in targets:
    print(x["id"], x["title"], "form: pwd -> powder", "(locked)" if x.get("locked") else "")
    if DRY_RUN:
        continue
    with elab.items.entry(x["id"]).unlocked() as entry:   # unlock if locked, restore afterwards
        entry.fields.update({"form": "powder"})
  • From the second run on, all(full=True, cache_dir=...) only re-reads changed entries, so running the dry run and then the real run is fast.
  • To roll back, write the saved JSON back with entry.metadata.update(saved, overwrite=True).
  • With many entries, first do a real run on a few, such as targets[:3].

Attaching files to many entries ​

Example: attach the files under data/<title>/ to the item with the same title.

python
from pathlib import Path
import elabftw_toolkit

elab = elabftw_toolkit.client("your-team-name")
DRY_RUN = True

id_by_title = {x["title"]: x["id"] for x in elab.items.all(category_title="Sample")}

for folder in sorted(p for p in Path("data").iterdir() if p.is_dir()):
    item_id = id_by_title.get(folder.name)
    files = sorted(p for p in folder.iterdir() if p.is_file())
    if item_id is None:
        print("no matching item:", folder.name)
        continue
    print(item_id, folder.name, [p.name for p in files])
    if DRY_RUN:
        continue
    with elab.items.entry(item_id).unlocked() as entry:
        uploaded = entry.files.upload(files, skip_if_same=True)   # identical files are skipped
        print("  uploaded:", uploaded)

Because skip_if_same=True (the default), re-running after an interruption uploads only what is left.

Exporting in bulk (CSV list, attachments, ELN) ​

python
from pathlib import Path
import pandas as pd
import elabftw_toolkit

elab = elabftw_toolkit.client("your-team-name")
entries = elab.items.all(full=True, category_title="Sample", cache_dir="cache")

# 1. Field values as CSV (utf-8-sig if it will be opened in Excel)
rows = [{"id": x["id"], "title": x["title"], **elabftw_toolkit.extra_fields(x)} for x in entries]
pd.DataFrame(rows).to_csv("samples.csv", index=False, encoding="utf-8-sig")

# 2. Per entry: attachments as zip, the whole record as .eln
out = Path("export")
for x in entries:
    entry = elab.items.entry(x["id"])
    if x.get("uploads"):
        entry.files.download_all_zip(out / f"{x['id']}_files.zip", overwrite=True)
    entry.download(item_title=x["title"], file_path=out, formats=("eln",))

For Experiments, use elab.experiments.all(...) and entry.download(experiment_title=..., ...). For MaiML export, see 10. MaiML.

Creating an Experiment and linking it to a sample ​

python
exp_id = elab.experiments.init(
    title="2026T0001-XAFS-SAMPLE-001",
    template_name="Measurement test",
    category_id=elab.experiments.categories.id("Measurement"),
    fail_if_title_exists_in_category=True,
)
exp = elab.experiments.entry(exp_id)
exp.set_item_field_and_link(field_name="sample_id", item_title="SAMPLE-001", item_category_title="Sample")
exp.files.upload("spectrum.dat")
exp.lock()

Apache License 2.0