TECHNOLOGIESTieInn Technologies

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/dump work with files; loads/dumps with strings.
  • to_csv writes the index as a column unless you pass index=False.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Files and JSON for pipelines

  1. Question 1easy

    You have JSON in a Python string variable text. Which function turns it into a dict?

  2. Files and JSON for pipelines

  3. Question 2medium

    Why do data pipelines prefer Parquet over CSV for storing tables?

  4. Files and JSON for pipelines

  5. 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))
  6. Files and JSON for pipelines

  7. Question 4medium

    What does this print?

    import json
    record = {"id": 7, "tags": ["new", "sale"]}
    back = json.loads(json.dumps(record))
    print(back == record)
  8. Files and JSON for pipelines

  9. Question 5hard

    Flatten payload to one row per item with columns sku, qty, and order_id. Store the DataFrame in result.

    Store your answer in result.

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.