Reading preferences
Concept

CSV, JSON, XML, and YAML

Choose a data format and read values without confusing text with types.

python, csv, json, xml, yaml, data

Match the shape of the data

CSV represents rows and fields, JSON represents nested values, XML represents tagged elements, and YAML is a flexible human-readable format. They do not all preserve the same types or structure. Parsing is not validation: check the expected keys, types, sizes, and acceptable values after reading.

Python illustration

import csv
import io
import json

text = "name,score\nAda,4\nLin,7\n"
rows = list(csv.DictReader(io.StringIO(text)))
scores = [int(row["score"]) for row in rows]
encoded = json.dumps({"scores": scores})
decoded = json.loads(encoded)
print(rows[0]["score"], type(rows[0]["score"]).__name__)
print(decoded["scores"])

Prepared output — not live execution:

4 str
[4, 7]

CSV gives this score as text. The program explicitly converts it before serialising the list to JSON and reading it back.

See the reasoning

Follow the example one step at a time

Trace one CSV field through conversion and a JSON round trip. This is a prepared teaching demonstration, not live code execution.

Read CSV rows

name,score
Ada,4
Lin,7

The header names two fields and each following line provides one row.

Read and write carefully

When opening CSV files, use open(path, newline="", encoding="utf-8") so the csv module handles newlines correctly. DictWriter can write named columns; json.load and json.dump read and write file objects, while loads and dumps work with strings. JSON object keys are strings; not every Python object can be encoded directly.

For trusted XML, xml.etree.ElementTree.fromstring parses text into elements whose tags, attributes, and children can be inspected. Treat untrusted XML carefully: consult the security guidance, use suitable hardened parsing and resource limits, and validate inputs.

from xml.etree import ElementTree

root = ElementTree.fromstring('<note priority="high"><title>Read</title></note>')
print(root.attrib["priority"])
print(root.findtext("title"))

For this trusted, fixed example, the prepared output is high and Read on separate lines. Missing elements and unexpected structures require handling.

YAML support is not in Python's standard library. In a separate environment with the third-party PyYAML installed, yaml.safe_load(text) reads ordinary data without arbitrary Python object construction. Even safe loading does not replace input-size limits and application validation. Never use eval to parse data or an unrestricted YAML loader on untrusted input.

import yaml  # PyYAML, installed separately

data = yaml.safe_load("title: Read\nscore: 4\n")
print(data["title"], data["score"])

The prepared output for this example is Read 4. Check the resulting structure and types before relying on them.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does csv.DictReader normally return for a field value?
2. What does json.loads do?
3. What should you consider before parsing untrusted XML?
4. What is the safer PyYAML loader for ordinary data?

References and further reading