Python
Summary - CSV and JSON
Combine csv.DictReader and json.dump to write a config file.
Summary - CSV and structured data
In this group you learned CSV reading/writing and structured data format operations. For CSV, csv.reader gives rows as lists and csv.DictReader as dicts. To write you use csv.writer with writerow/writerows.
For the structured data format on files use json.load/json.dump; for strings use json.loads/json.dumps. ensure_ascii=False handles Turkish characters; indent=2 gives readable indentation. Always include encoding="utf-8" when opening files.
Mini task: write structure to file
In the summary task you write structured data to a file and load it back. You keep a list inside a dict — a pattern common in real applications. You write with json.dump and read with json.load.
The task shows both the read-write loop and Turkish-character preservation together. The output is the count of items in the restored list, proving the data survived intact.
Exercise Write and read a dict with a list
Start with import json. Define a dict with data = {"name": "Ayşe", "friends": ["Ali", "Veli"]}. Write it with with open("social.txt", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2). Then read it back with with open("social.txt", "r", encoding="utf-8") as f: loaded = json.load(f). Print the friend count with print(len(loaded["friends"])).
Show example solution
import json
# Define a data dict (with a list inside)
data = {"name": "Ayşe", "friends": ["Ali", "Veli"]}
# Write to file, read back, print list length
with open("social.txt", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("social.txt", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(len(loaded["friends"]))
Test yourself
-
Which method reads CSV as dictionaries?
- csv.writer
- csv.reader
- csv.DictReader
- csv.DictWriter
Show answer
csv.DictReader — Csv.DictReader. This method reads rows as dictionaries.
-
json.dump writes to a file
import json
data = {"name": "Veli"}
with open("v.txt", "w", encoding="utf-8") as f:
json.____(data, f, ensure_ascii=False)
Show answer
import json
data = {"name": "Veli"}
with open("v.txt", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
-
Match the module uses
- csv.reader
- CSV row as list
- csv.DictReader
- CSV row as dict
- json.load
- Reading from a file
- json.dumps
- Writing to a string
Next lesson: Path