- LPU MCA Semester 1
- CAB106
- Unit 5
CAB106 · Unit 5: Exception handling and file management
Working with CSV and JSON files
11 practice questions
Key points
- csv.reader returns lists of strings; DictReader returns dictionaries
- dumps/loads use strings; dump/load use files
- JSON turns True into true, None into null and tuples into lists
- JSON object keys are always strings
CSV stores rows of comma-separated text. The csv module reads and writes it: csv.reader yields each row as a list of strings (the header is just the first row), csv.DictReader yields dictionaries keyed by the header names, and csv.writer / DictWriter write rows, quoting fields that contain the separator, such as "b,c". Use io.StringIO to treat text as a file, and convert fields with int() before arithmetic.
JSON is a text format for nested data. The json module converts between Python objects and JSON text.
| Function | Purpose |
|---|---|
json.dumps(obj) | Python object to JSON string |
json.loads(text) | JSON string to Python object |
json.dump(obj, f) | Write JSON to a file |
json.load(f) | Read JSON from a file |
Type mapping: True/False/None become true/false/null, strings use double quotes, tuples become arrays (lists) on the way back, and object keys are always strings, so {1: 'a'} returns as {'1': 'a'}. sort_keys=True orders keys alphabetically and invalid text raises json.JSONDecodeError.
Exam trap: load works on a file object and loads on a string; the final s means string.
Try two questions
Which standard module reads and writes comma-separated values files?
- cvs
- comma
- table
- csv
Show the answer
D. The csv module provides reader, writer, DictReader and DictWriter.
Why not A: cvs is a misspelling and not a Python module.
Why not B: There is no standard module called comma.
Why not C: There is no standard module called table.
What is the difference between json.load and json.loads?
- load parses a string, and loads reads from a file object
- load writes JSON, and loads writes it to a string
- load keeps key order, and loads sorts every key
- load reads from a file object, and loads parses a string
Show the answer
D. The s in loads stands for string.
Why not A: The two roles are reversed in this option.
Why not B: Writing is done by dump and dumps.
Why not C: Neither function sorts keys unless asked.