Read / Edit / Write 循环
了解 Claude Code 如何安全地修改您的文件。
Read / Edit / Write 循环 是 CoddyKit 上的免费 Claude Architect 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Claude Architect 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Claude Architect 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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%).
常见问题解答
「Read / Edit / Write 循环」课时是免费的吗?
是的 — 「Read / Edit / Write 循环」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Claude Architect 课程的其余内容,请升级到 CoddyKit PRO。 Claude Architect 课程共包含 4 节课。
「Read / Edit / Write 循环」这节课中我会学到什么?
了解 Claude Code 如何安全地修改您的文件。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Claude Architect 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Claude Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「Read / Edit / Write 循环」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Claude Architect 课中编写并运行代码吗?
能。每节 Claude Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 什么是 Claude Code
- 交互式与无头模式
- Read / Edit / Write 循环
- 记忆与压缩命令