Day 4 of 760 minCipher Cadet

Day 4: Cleaning Output Into Structured Data

Taught by Mr Elite Updated

By the end of today you can

  • Explain why structured data beats scrolling through raw output
  • Read a raw file in Python and pick out named fields
  • Write findings.json and findings.csv from a script you wrote
  • Check cleaned entries against the raw files and record any mismatch

Warm-up

Answer from memory first, then tap to check. Recalling yesterday is what makes it stick.

What does curl -I fetch, and what does curl -s do?

curl -I fetches only the response headers. curl -s hides the progress meter so the output stays clean.

Why do we never edit the files in the raw folder?

Raw output is evidence. If you change it, you can no longer prove what the target actually returned, so cleaning goes in a separate folder.

Yesterday you saved raw files. Open one now and you will see a wall of headers or HTML. Finding the server name in that is easy once. Doing it across thirty files, every week, is where people lose the plot and miss things.

Today I will show you how to read those raw files with a short Python script and pull out the useful fields into a tidy file. Later days hand that tidy file to an AI, so what we build today decides how good the summary can be. Everything runs against your own raw folder and your own local server.

Why structure beats scrolling

Raw output is written for programs to send and receive, not for you to read. A header block, a page of HTML and a script log all look different, so you have to re-learn the shape of each one every time you open it.

Structured data means every item has the same named fields. One item might be a response, with a status, a server name, a content type and a title. Once everything has the same shape, you can sort it, count it, search it and hand it to another tool without guessing.

Field
One named piece of information, such as server or status.
Item
One record made of several fields, for example one response you collected.
JSON
A text format for structured data, written as names and values inside curly brackets. Easy for programs and readable by people.
CSV
Comma separated values. A plain text table that opens in any spreadsheet.
Parsing
Reading raw text and picking the fields out of it by following its pattern.

Quick check

Why do we convert raw output into items with the same fields?

Reading a file and picking out fields

Python can open a file and give you its text as one string. From there you cut the string up. For headers, each line looks like name, colon, value, so we split on the first colon. For HTML, the title sits between two tags, so we use a small pattern match.

A pattern match here is called a regular expression, or regex. It describes text you want to find. We only need two tiny ones today, and I will explain each as we use it. Any file that does not match gives us an empty result, so we will always plan for a missing field.

Watch me do it: raw files to findings.json

I am assuming your project folder looks like Day 3, with a raw folder holding at least a saved headers file and a saved page. Mine are raw/headers_root.txt (from curl -I) and raw/page_root.html. Yours may have different names. The script I show you works out the type from the contents, so the names do not matter. Everything here touches only your own files.

python
import csv
import json
import re
from pathlib import Path

RAW = Path("raw")
CLEAN = Path("clean")
CLEAN.mkdir(exist_ok=True)

def parse_headers(text):
    lines = text.splitlines()
    status = int(lines[0].split()[1])
    headers = {}
    for line in lines[1:]:
        if ":" in line:
            name, value = line.split(":", 1)
            headers[name.strip().lower()] = value.strip()
    return status, headers
Block 1. Sets up the folders. parse_headers takes the status from the first line, then splits each other line at the first colon into a lowercase name and its value.
python
def parse_page(text):
    m = re.search(r"<title>(.*?)</title>", text, re.I | re.S)
    title = m.group(1).strip() if m else None
    links = len(re.findall(r"<a\s", text, re.I))
    return title, links

items = []
for path in sorted(RAW.iterdir()):
    if path.name == "NOTES.txt":
        continue
    text = path.read_text(errors="replace")
    item = {"source_file": path.name, "kind": "other",
            "size_bytes": path.stat().st_size, "status": None,
            "server": None, "content_type": None,
            "title": None, "link_count": None}
    if text.startswith("HTTP/"):
        status, h = parse_headers(text)
        item.update(kind="headers", status=status,
                    server=h.get("server"),
                    content_type=h.get("content-type"))
    elif "<html" in text.lower():
        title, links = parse_page(text)
        item.update(kind="page", title=title, link_count=links)
    items.append(item)
Block 2. The regex (.*?) means the shortest text between those two tags. Each file becomes one item with the same eight fields. Fields that do not apply stay None.
python
with open(CLEAN / "findings.json", "w") as f:
    json.dump(items, f, indent=2)

if items:
    with open(CLEAN / "findings.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(items[0].keys()))
        w.writeheader()
        w.writerows(items)

print(f"Wrote {len(items)} items to clean/findings.json")
Block 3. json.dump writes the list as indented JSON. DictWriter writes the same items as CSV rows under a header line. The final print confirms how many items were saved.

Now open clean/findings.json in VS Code. You should see something like this, with your own values:

json
[
  {
    "source_file": "headers_root.txt",
    "kind": "headers",
    "size_bytes": 172,
    "status": 200,
    "server": "SimpleHTTP/0.6 Python/3.11.4",
    "content_type": "text/html",
    "title": null,
    "link_count": null
  }
]
One item from the output, trimmed to the headers entry. The null values are fields that do not apply to a header file.

Quick check

In the script, why is a missing title stored as None rather than an empty guess like "Home"?

Your turn: extend it and prove it

Now make the script yours. Do all of this on your own raw files and your own local target, never on anyone else's site.

Why checking matters

A script is only a set of instructions you wrote, and it can be wrong in quiet ways. A regex might grab the wrong tag. A header might be split in the wrong place. The script will still print a cheerful success message.

Comparing a few entries to the raw files is how you catch that. It is the same habit you will need when an AI summarises your data, because a summary can sound confident and still be wrong. Today you practise that check on your own code, where the answer is easy to find.

Quick check

Your findings.json says the server is Apache, but the raw headers file says SimpleHTTP. What do you trust and do?

If it did not work

Running clean.py from the wrong folder, so Python cannot find raw

The paths are relative. Run pwd and ls first. You must be in the folder that contains both raw and clean.py.

Editing a raw file to fix a parsing problem

Fix the script instead. Raw files are evidence and stay exactly as collected.

Filling a missing field with a guess so the table looks complete

Leave it as None. A visible gap is honest and can be investigated.

Trusting the success message without comparing against raw

Always check at least three entries by eye. The print line only counts items, it does not prove they are correct.

Forgetting that headers are case-insensitive, so Content-Type is missed

The script lowercases header names. Look up names in lowercase, such as content-type.

Recap

  • Structured data gives every item the same named fields, so it can be sorted, counted and checked.
  • A script reads from raw and writes to clean, never the other way round.
  • Missing data is stored as null, not as a guess.
  • JSON suits programs and nested data, CSV suits spreadsheets, and one script can write both.
  • Cleaning is a step that can be wrong, so compare a few entries against the raw files every time.
  • Write down any mismatch you find, because it shows where your script needs work.

Cheat sheet

Path("raw").iterdir()
Lists every file in the raw folder.
path.read_text(errors="replace")
Reads a file as text without crashing on odd characters.
line.split(":", 1)
Splits a line at the first colon only, giving name and value.
re.search(pattern, text)
Finds the first piece of text matching a pattern, or None.
json.dump(items, f, indent=2)
Writes a list of items as readable JSON.
csv.DictWriter
Writes a list of dictionaries as CSV rows.
grep -i word file
Searches a file for a word, ignoring case. Handy for checking against raw.

Before the next day

Mission: clean.py and a three-entry check

Write clean.py so it reads your Day 3 raw files and writes findings.json with at least five fields per item. Then prove it works by comparing three entries against the raw files. This gives you the trusted data file that Day 5 will pass to an AI.

About 30 min

You are done when: A clean.py script, a clean folder holding findings.json (and findings.csv), and a CHECK.txt recording three comparisons against raw.

Want more? Add a field that counts how many headers the response had, then add a simple check at the end of clean.py that prints a warning for any item where the status is None.

Quiz

4 questions. Your score is saved with your progress.

1. What is the main reason to turn raw output into structured data?

2. Your script reads raw/page_root.html but finds no title tag. What should findings.json hold for title?

3. Which folder layout follows today's rule?

4. You compare three entries and one has the wrong content type. What is the right next step?

Finish the day

Mark the day complete to save your progress.

Go to Day 5

Next: Day 5 hands your findings.json to an AI and asks it for a short, ordered summary. You will also learn to verify every claim it makes against the data you cleaned today.

Tell someone you are doing this:WhatsAppXLinkedIn

Your notes

Private to this device. Write what you want to remember from today.