0Pricing
Claude Architect · Lezione

Il ciclo Read / Edit / Write

Scopra come Claude Code modifica i suoi file in sicurezza.

Il ciclo Read / Edit / Write è una lezione Claude Architect gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Claude Architect, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Claude Architect include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why a Loop, Not a Magic Wand

Claude Code never silently rewrites your files from memory. It changes code through a disciplined cycle of three built-in tools: Read, Edit, and Write.

This loop exists for one reason: safety. The model only edits text it has actually loaded, so changes are grounded in the real file on disk, not in a hallucinated version of it.

In this lesson you will learn how each tool behaves, when Claude picks one over another, and the failure modes the exam expects you to recognize.

The Built-in Tool Family

Claude Code ships with a small, deliberate set of file tools. Each has a sharp purpose:

  • Glob — find files by pattern, e.g. **/*.test.tsx
  • Grep — search file contents
  • Read — load one file into context
  • Edit — make a precise, unique-match change
  • Write — create a file (or fully replace one)
  • Bash — run shell commands

The write loop is the heart of this set: you Read to ground, then Edit or Write to change.

Read First — Always

Read loads a file's current contents into the model's context. This is the non-negotiable first step before any modification.

Why? Because Edit works by matching exact text. If Claude has not seen the file, it cannot know the precise string to replace, and it would be guessing at indentation, imports, and surrounding lines.

Grounding the edit in the real file is what keeps the change correct instead of plausible-but-wrong.

from anthropic import Anthropic

client = Anthropic()

# Claude Code asks to load the file before touching it
tool_call = {
    "name": "Read",
    "input": {"file_path": "/app/services/billing.py"},
}
# The file's current text is returned and appended to history,
# so the next Edit can match an EXACT, real string.

Edit — The Precise Surgeon

Edit is the preferred tool for changing existing files. It takes an old_string and a new_string and swaps one for the other.

The key rule: the old_string must match exactly once. A unique match guarantees the edit lands in the right place and nowhere else. If the match is ambiguous or appears multiple times, the edit is rejected rather than risking the wrong line.

Edit is surgical: it preserves the rest of the file untouched.

tool_call = {
    "name": "Edit",
    "input": {
        "file_path": "/app/services/billing.py",
        "old_string": "def refund(amount):\n    return charge(-amount)",
        "new_string": "def refund(amount):\n    verify_identity()\n    return charge(-amount)",
    },
}
# Matches exactly once -> safe, targeted change.

When the Match Isn't Unique

What if old_string appears several times, or you cannot isolate a unique snippet? Edit will fail on purpose, because a non-unique match cannot be applied safely.

The documented fallback is: Read the file, then Write it back in full. By rewriting the whole file from the version Claude just read, the change is still grounded and the ambiguity disappears.

This Read + Write fallback is exactly the kind of practical detail the certification expects you to know.

# Edit failed: 'return result' appears 6 times.
# Fallback pattern:
#   1. Read the whole file (ground the content)
#   2. Write it back with the full, corrected text
tool_call = {
    "name": "Write",
    "input": {
        "file_path": "/app/utils/parse.py",
        "content": full_corrected_file_text,
    },
}

Write — Create or Replace

Write creates a brand-new file, or completely overwrites an existing one with new content.

Reach for Write when:

  • The file does not exist yet (a new module, config, or test).
  • The change is so sweeping that a full rewrite is clearer than many Edits.
  • An Edit could not find a unique match (the fallback from the previous scene).

For small, targeted changes to existing files, prefer Edit — it is lower risk because it leaves everything else exactly as it was.

tool_call = {
    "name": "Write",
    "input": {
        "file_path": "/app/services/__tests__/billing.test.py",
        "content": "def test_refund_verifies_identity():\n    ...",
    },
}
# New file -> Write is the right choice (no existing text to Edit).

The Loop Inside the Agentic Loop

Read / Edit / Write are tool calls, so they ride on the standard agentic loop: send the request, inspect stop_reason, and if it is tool_use, run the tool, append the result to history, and send again.

The model keeps no state between turns — you resend the full message history every request, including each tool result. That is how the just-Read file content stays available for the next Edit.

You terminate when stop_reason becomes end_turn, never by scanning the text for words like "done".

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=2048,
    messages=history,   # FULL history every turn
    tools=tools,
)

if resp.stop_reason == "tool_use":
    # run Read/Edit/Write, append the tool_result, loop again
    history.append(run_tool(resp))
elif resp.stop_reason == "end_turn":
    done = True   # terminate on the stop reason, not on parsed text

Investigate Before You Edit

Good edits start with good discovery. The recommended incremental pattern is:

Grep entry points → Read the files → Grep usages → Read the consumers.

You narrow down where a change belongs before loading large files, which keeps context lean and the edit precise. Use Glob to locate files by name pattern and Grep to find the symbol inside them.

Only after you understand the surrounding code do you Read the exact target and apply an Edit.

# 1) Find where the function lives
#    Grep: "def process_refund"
# 2) Read that file
# 3) Find every caller
#    Grep: "process_refund("
# 4) Read the consumers, then Edit with full context
glob = {"name": "Glob", "input": {"pattern": "**/billing*.py"}}

Plan Mode for Big Changes

Not every change should jump straight into Edit/Write. Plan mode lets Claude explore safely and propose a plan for your approval before any file is modified.

Use plan mode when the work is large, spans multiple files, involves an architectural decision, or has several possible approaches.

Use direct execution for single-file fixes or a clear stack trace — planning there is just overhead. An Explore subagent can isolate noisy discovery output so it does not flood your main context.

Multi-File Edits: Review in Two Passes

When a change touches many files, resist the urge to review everything in one sweep. A single-pass multi-file review dilutes attention and misses cross-file bugs.

The exam-blessed pattern is two passes:

  • Per-file local pass — correctness of each file on its own.
  • Separate cross-file integration pass — how the edited files fit together (shared signatures, imports, contracts).

The same discipline that makes individual Edits precise makes a batch of Edits trustworthy.

Guardrails the Loop Can't Provide

The Read / Edit / Write loop makes changes grounded and precise — but it is still model-driven and probabilistic (~90% reliable), not a guarantee.

When a file change must obey a hard rule (security policy, license header, forbidden API), don't rely on a prompt alone. Use deterministic enforcement:

  • .claude/rules/ files with paths frontmatter load only when matching files are edited.
  • Hooks (e.g. PostToolUse) enforce policy 100% deterministically.

Prompts guide; hooks guarantee. Reach for hooks when failure has financial, legal, or safety consequences.

---
paths:
  - "src/payments/**"
---
# Loaded ONLY when editing payment files.
# Every refund path must call verify_identity() before charge().
# Critical money rules: enforce with a PostToolUse hook too —
# prompts are ~90%, hooks are 100%.

Quick Check: Picking the Right Tool

You ask Claude Code to rename a helper that is called in 9 places across one file. Claude reads the file and tries an Edit whose old_string is just result — but that token appears many times, so the Edit is rejected for a non-unique match. What is the correct next move?

Recap: The Safe Write Loop

Key takeaways:

  • Read before you change — edits must be grounded in the real file, never the model's memory.
  • Edit is the precise default: it requires a unique match and leaves the rest of the file untouched.
  • When the match isn't unique or the file is new, fall back to Read + Write (or just Write for new files).
  • These tools ride the agentic loop: full history every turn, terminate on stop_reason, never on parsed text.
  • Investigate first (Grep → Read → Grep → Read); use plan mode for big changes and a two-pass review across files.
  • For hard rules, back the loop with rules files and hooks — prompts guide (~90%), hooks guarantee (100%).

Domande Frequenti

La lezione «Il ciclo Read / Edit / Write» è gratuita?

Sì — il testo completo di «Il ciclo Read / Edit / Write» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Claude Architect, passa a CoddyKit PRO. Il corso Claude Architect include 4 lezioni in totale.

Cosa imparerò in «Il ciclo Read / Edit / Write»?

Scopra come Claude Code modifica i suoi file in sicurezza. Eserciti Claude Architect con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Claude Architect?

Non è richiesta alcuna esperienza precedente. Claude Architect su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Il ciclo Read / Edit / Write»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Claude Architect?

Sì. Ogni lezione Claude Architect include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Che cos’è Claude Code
  2. Interattivo vs headless
  3. Il ciclo Read / Edit / Write
  4. Comandi Memory e Compact
← Torna a Claude Architect