Skip to content

11. よくある作業の手順集 ​

たくさんの entry をまとめて扱うときの手順です。どの手順も、次の 3 つを守ると安全です。

  1. まず DRY_RUN = True で実行し、何が起きるかを print で確かめる。 よければ False にして本番。
  2. 何度実行しても同じ結果になるように書く(既にあるものは作らない、同じファイルは upload しない)。途中で止まっても、もう一度実行すればよくなります。
  3. 最初は検証用の team / category で試す。

以下では、次のように client を作ってあるものとします。

python
import elabftw_toolkit

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

CSV / Excel から Resource item をまとめて登録する ​

samples.csv の 1 行が 1 つの item、title 列が表題、ほかの列名が eLabFTW の項目名と同じ、という前提です。

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

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

df = pd.read_csv("samples.csv", dtype=str).fillna("")
# Excel なら: df = pd.read_excel("samples.xlsx", dtype=str).fillna("")   # openpyxl が必要

category_id = elab.items.categories.id(CATEGORY)
existing = {x["title"] for x in elab.items.all(category_title=CATEGORY)}   # 一覧を 1 回だけ取る

for row in df.to_dict("records"):
    title = row.pop("title")
    if title in existing:
        print("skip(既にある):", title)
        continue
    if DRY_RUN:
        print("作成予定:", 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)    # 列名 = 項目名
    existing.add(title)
    print("作成:", new_id, title)
  • fields.update() は既定で template に無い項目名を拒否します(ValueError)。列名の打ち間違いに気づけます。
  • 1 件ずつ find() で調べるより、最初に all() で title の集合を作る方がずっと速いです。
  • 実験ノートも同じ形で elab.experiments.init(...) を使えます(重複を防ぐなら fail_if_title_exists_in_category=True)。

多くの entry の項目を安全に書き換える(dry-run つき) ​

例: category「試料」で form が powder の item を 粉末 に直す。

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="試料", cache_dir="cache")
targets = [x for x in entries if elabftw_toolkit.extra_fields(x).get("form") == "powder"]
print(len(targets), "件が対象")

# 変更前の metadata を保存しておく(戻すときに使う)
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: powder -> 粉末", "(locked)" if x.get("locked") else "")
    if DRY_RUN:
        continue
    with elab.items.entry(x["id"]).unlocked() as entry:   # lock されていれば外して戻す
        entry.fields.update({"form": "粉末"})
  • all(full=True, cache_dir=...) は 2 回目から変わった entry だけを読み直すので、dry-run と本番を続けて実行しても速いです。
  • 戻すときは、保存した JSON を entry.metadata.update(saved, overwrite=True) で書き戻します。
  • 件数が多いときは、最初に targets[:3] などで少しだけ本番を試してください。

多くの entry にファイルを添付する ​

例: data/<表題>/ の下にあるファイルを、同じ表題の item に添付する。

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="試料")}

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("対応する 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)   # 同じファイルはスキップ
        print("  upload:", uploaded)

skip_if_same=True(既定)なので、途中で止まってももう一度実行すれば残りだけを upload します。

まとめて書き出す(CSV 一覧・添付ファイル・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="試料", cache_dir="cache")

# 1. 項目の一覧を CSV に(Excel で開くなら utf-8-sig)
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. entry ごとに添付ファイルを zip に、記録全体を .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",))

実験ノートなら elab.experiments.all(...) と entry.download(experiment_title=..., ...) を使います。MaiML で書き出すときは 10. MaiML を見てください。

実験ノートを作って試料とつなぐ ​

python
exp_id = elab.experiments.init(
    title="2026T0001-XAFS-SAMPLE-001",
    template_name="計測試験",
    category_id=elab.experiments.categories.id("計測"),
    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="試料")
exp.files.upload("spectrum.dat")
exp.lock()

Apache License 2.0