La boucle Read / Edit / Write
Comment Claude Code modifie vos fichiers en toute sécurité.
La boucle Read / Edit / Write est une leçon Claude Architect gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Claude Architect, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Claude Architect comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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 textInvestigate 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 withpathsfrontmatter 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%).
Questions Fréquemment Posées
La leçon « La boucle Read / Edit / Write » est-elle gratuite ?
Oui — le texte complet de « La boucle Read / Edit / Write » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Claude Architect, passe à CoddyKit PRO. Le cours Claude Architect comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « La boucle Read / Edit / Write » ?
Comment Claude Code modifie vos fichiers en toute sécurité. Tu pratiques Claude Architect avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Claude Architect ?
Aucune expérience préalable n'est requise. Claude Architect sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « La boucle Read / Edit / Write » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Claude Architect ?
Oui. Chaque leçon Claude Architect inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Qu’est-ce que Claude Code
- Interactif ou sans interface
- La boucle Read / Edit / Write
- Commandes de mémoire et de compaction