0Pricing
Claude Architect · 강의

Read / Edit / Write 루프

Claude Code가 파일을 안전하게 변경하는 방법을 알아봅니다

Read / Edit / Write 루프은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 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%).

자주 묻는 질문

“Read / Edit / Write 루프” 강의는 무료인가요?

네 — “Read / Edit / Write 루프” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

“Read / Edit / Write 루프”에서 뭘 배우나요?

Claude Code가 파일을 안전하게 변경하는 방법을 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Claude Architect을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“Read / Edit / Write 루프” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Claude Code란 무엇인가
  2. 대화형 실행과 헤드리스 실행
  3. Read / Edit / Write 루프
  4. 메모리 및 Compact 명령
← Claude Architect(으)로 돌아가기