Skip to main content
← All posts
Overhead shot of an East Asian developer at a warm wooden desk at night, one hand on a mechanical keyboard, screens showing a long AI conversation and a folder of extracted code files under a coral-lit desk lamp.
·7 min read

How to Extract Code Blocks From AI Conversations Into Runnable Files

A practical workflow for pulling code blocks out of ChatGPT, Claude, and Gemini answers into named, runnable files without losing the surrounding reasoning.

Ask any coding assistant a real question and you get back a small essay wrapped around three or four code blocks. The prose is useful the first time you read it. After that, what you want are the files. You want the Python function in a .py, the SQL migration in a .sql, the Dockerfile in a Dockerfile, and the shell one-liner in a script you can chmod and forget. Copy-pasting each block by hand is fine once. Do it ten times a day and it becomes the slowest part of your workflow. This post walks through how to pull code blocks out of AI conversations cleanly, name them, and drop them into a project without losing the surrounding reasoning, because the explanation is often the reason the code works.

Why the Copy Button Is Not Enough

Every major chat interface ships a copy button on each code fence, and it works fine for one snippet. The problem starts when a single answer contains a shell command, a config file, and a patch to an existing module, and you need all three in different places on disk. The copy button gives you the code but strips the filename hint the model wrote in the preceding sentence. You end up naming files from memory, and half of them land as untitled-3.py in your Downloads folder. A week later you cannot tell which one was the good version.

There is also the question of language detection. ChatGPT and Claude both label most fences correctly, but Gemini and DeepSeek still ship plenty of untagged blocks, especially for TOML, YAML, and shell. When you paste an untagged block into a new file with the wrong extension, your editor stops helping you. Syntax highlighting goes flat, the linter goes quiet, and small typos survive longer than they should. A proper extraction step catches this before it costs you an afternoon of debugging a config that was fine three characters ago.

The last reason is provenance. Six weeks after the conversation, you will not remember which prompt produced the regex that is now sitting in production. If you extract code blocks in a way that preserves a link back to the source conversation, that question takes ten seconds instead of an hour. Our guide on how to cite AI conversations in research covers the citation side of this in more detail. The same discipline applies to a Friday afternoon patch, not only to a formal paper.

The Manual Workflow That Scales

Before reaching for a script, it helps to have a manual workflow that is fast enough to use every day. The version I keep coming back to has four steps, and it works in any editor without any tooling beyond a shell and a scratch folder. It is boring, which is why it survives. Fancy pipelines break the moment your assistant switches vendor or format, but four ordered steps in your head do not.

  • Export the conversation as markdown, either through the built-in export or by pasting it into a reader like Prism MD.
  • Skim the prose once and mentally tag which blocks are worth keeping, since a lot of code in AI answers is illustrative and does not need a file of its own.
  • For each keeper, name the file before you copy the block. The name usually comes from the sentence right above the fence, or from a filename the model already suggested in backticks.
  • Drop each named file into a scratch folder named after the conversation slug or date, so future you can find the source.

The scratch folder is the important part of the whole approach. It creates a single place where every extracted snippet from a given chat lives together, next to a copy of the original conversation in markdown. When you come back to the code in a week, the reasoning is right there next to it, and you do not have to guess at what the model was solving for. This is the same instinct behind our guide on building a personal knowledge base from AI conversations, scoped down to a single session.

When to Automate the Extraction

Automation earns its keep the moment you start extracting from long research sessions or agent transcripts. A single Claude Code run can produce dozens of code blocks across a dozen files, and no human wants to click copy that many times in a row. At that point, a small parser saves real hours over the course of a week. The break-even is somewhere around fifteen fences per session, which sounds high until you look at your last agent trace.

The parser does not need to be clever. Markdown fenced code blocks are one of the easiest formats to tokenize, since they are delimited by triple backticks with an optional language tag. A twenty-line Python script using the markdown-it-py library, or a Node script using remark, will walk the tree, pull each fence, and write it to disk. The official CommonMark spec is worth skimming once so you handle the edge cases around indentation and nested fences without surprises.

The filename problem is where a little cleverness pays off. Two heuristics cover most cases in practice. First, look at the sentence immediately before the fence for a phrase like "save this as", "create a file called", or a bare filename in backticks. Second, if that fails, use the language tag plus an index, so an untagged block after a Python block becomes snippet-02.txt rather than a silent collision on disk. Neither heuristic is perfect, but together they get you above ninety percent without a language model in the loop.

Handling Diffs, Patches, and Multi-File Answers

Coding assistants have gotten much better at emitting diffs and patch files rather than full file rewrites. That is a win for context length, but it complicates extraction. A unified diff is not a runnable file on its own. It needs to be applied with git apply or patch -p1, and it will fail loudly if the base file has drifted since the conversation started. Extraction is the easy part, and application is where the real work lives.

The workflow I use for diffs is to save the patch to a file, run git apply --check first, and only apply if the check passes. If the check fails, the answer is usually to open the conversation in a reader that handles long context well and ask the model for a fresh rebase against the current HEAD. Our post on reading long Claude conversations without losing the thread covers how to keep that kind of iteration organized when the chat gets deep. The tighter your reading loop, the less painful the rebase conversation becomes.

Multi-file answers deserve their own convention. When an assistant writes out four files in one response, I keep them in a single markdown file with the fences intact, then run the extractor once with a --multi flag. That way the fallback is always a readable document, not a pile of loose files without context. If the extractor breaks on a weird edge case, I still have the source markdown to work from. That safety net has saved me more than once during a late-night deploy.

FAQ

Does this work for Jupyter notebook cells? Yes, with one extra step. Notebook cells export as JSON rather than markdown fences, so extract them to .py or .ipynb via a small nbconvert call after the initial pass. Most assistants will happily emit notebook JSON if you ask for it directly. The tradeoff is that JSON is harder to eyeball in a reader, so I keep both formats when a notebook matters.

What about secrets that end up in a code block? Scrub them at extraction time, not later. A pre-commit hook with detect-secrets or gitleaks catches API keys, tokens, and connection strings before they land in a repo. Assume every AI conversation will eventually be shared, and write the extractor accordingly. Adding the scan as a step in the extractor itself, rather than trusting the commit hook, closes the gap for scratch folders that never get committed.

Can I keep the surrounding prose alongside the code? That is the point of a good reader. Tools built for this, like Prism MD, render the fences with a copy button and keep the explanation right next to them, so you never lose the reasoning when you grab the file. The prose and the code are two halves of the same answer, and treating them separately is what makes AI code hard to reuse. Keeping them stitched together turns one-shot answers into a durable reference.

Read your AI code the way it was meant to be read.

Free to start — no credit card.

Try Prism MD free

Related reading

Ready to read your own AI documents?

Open ChatGPT, Claude, Gemini, or any markdown file in the reader built for the way models write.

  • Renders code, math & Mermaid out of the box
  • Works offline once you've opened a doc
  • Free forever for personal reading