Guide Python Intermediate

8.12 Type Conversion in File Handling

Why input(), CSV, JSON, and YAML data all require explicit conversion on the way in — and the specific gap between JSON's real type inference and a JSON field written as a string.

2 min read

Every one of these external data sources hands over strings (or, for JSON, occasionally the wrong type) — converting on the way in is a universal pattern.

Reading User Input

input() always returns str, regardless of what’s typed — explicit conversion is mandatory before any arithmetic.

>>> age_str = input("Enter age: ")     # ALWAYS str, even for '25'
>>> age = int(age_str)
>>> age + 1
26

CSV Data

The csv module reads every field as str, with no automatic type inference — numeric fields must be explicitly converted after reading.

>>> import csv, io
>>> row = next(csv.DictReader(io.StringIO("name,age\nAlice,30")))
>>> row, type(row["age"])
({'name': 'Alice', 'age': '30'}, <class 'str'>)
>>> age = int(row["age"])
>>> age, type(age)
(30, <class 'int'>)

JSON Data

Unlike CSV, json.loads() does infer types automatically for genuine JSON numbers/booleans — but a field written as a JSON string ("8080" instead of 8080) still needs manual conversion.

>>> import json
>>> data = json.loads('{"port": "8080"}')     # port is a JSON string here
>>> type(data["port"])
<class 'str'>
>>> port = int(data["port"])
>>> port, type(port)
(8080, <class 'int'>)

YAML Data

PyYAML’s safe_load() generally infers types well (numbers, booleans, and null all come back as their proper Python types) — but values explicitly quoted in the YAML source still arrive as str and may need conversion, same as JSON.

Quick Interview Answer

“Every external text-based data source needs the same discipline: input() always returns str, no exceptions. The csv module never infers types at all — every field is str regardless of content. json.loads() and YAML’s safe_load() do infer real types for genuine JSON/YAML numbers and booleans, but a value that was written as a quoted string in the source — like \"8080\" instead of 8080 — comes back as str even though it looks numeric, and still needs an explicit conversion after parsing.”

Common Mistakes

  • Assuming csv.DictReader infers numeric columns — it never does; every field is str until explicitly converted.
  • Assuming every JSON number field is automatically an int/float in Python — only true if it was written as a JSON number in the source, not as a quoted string.
  • Comparing a CSV or JSON string field directly against a number without converting first — see 8.13 Type Conversion in DevOps for the exact failure mode this causes.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form