Files and JSON for pipelines
Python · 15 questions
Short notes
Key idea
Read and write files with open inside a with block, which closes the file for you. JSON maps neatly onto Python dicts and lists.
Syntax
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
with open("out.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
import json
data = json.loads('{"a": 1}') # text → dict
text = json.dumps(data, indent=2) # dict → text
with open("data.json") as f:
data = json.load(f)
pd.read_json("orders.json"); pd.json_normalize(records)
df.to_csv("clean.csv", index=False)
Example
with open("orders.json", encoding="utf-8") as f:
orders = json.load(f)
df = pd.json_normalize(orders) # nested fields become columns like customer.city
The with block closes the file even if an error happens inside it.
Traps
"w"empties the file first; use"a"to append.- Always set
encoding="utf-8"on Windows, or ₹ and Tamil text may break. load/dumpwork with files;loads/dumpswith strings.to_csvwrites the index as a column unless you passindex=False.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
You have JSON in a Python string variable
text. Which function turns it into a dict? - Question 2medium
Why do data pipelines prefer Parquet over CSV for storing tables?
- Question 3medium
What does this print?
import pandas as pd payload = [ {"order_id": 1, "items": [{"sku": "A", "qty": 2}, {"sku": "B", "qty": 1}]}, {"order_id": 2, "items": [{"sku": "A", "qty": 5}]}, {"order_id": 3, "items": []}, ] rows = pd.json_normalize(payload, record_path="items", meta=["order_id"]) print(len(rows)) - Question 4medium
What does this print?
import json record = {"id": 7, "tags": ["new", "sale"]} back = json.loads(json.dumps(record)) print(back == record) - Question 5hard
Flatten
payloadto one row per item with columnssku,qty, andorder_id. Store the DataFrame inresult.Store your answer in
result.
Files and JSON for pipelines
Files and JSON for pipelines
Files and JSON for pipelines
Files and JSON for pipelines
Files and JSON for pipelines
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.