Python Mastery – From Basics to Brilliance / File Handling

Working with CSV & JSON

βœ… What is CSV?

Think of a CSV file like an Excel sheet, but instead of rows and columns, it uses commas to separate the values.

πŸ”Ή Example content of a CSV file:

Name,Age
Ravi,22
Amit,20
  • Each row represents a record (like a student).

  • Each column has a field (like name or age).

  • .csv files are great for tabular data like attendance, marks, sales, etc.


πŸ“– Reading a CSV File in Python

import csv

with open('students.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

βœ… Explanation:

  • import csv β†’ We use Python's built-in csv module.

  • open(..., 'r') β†’ Open the file in read mode.

  • csv.reader(...) β†’ Helps us read the file row by row.

  • for row in reader: β†’ Each row is a list of values like ['Ravi', '22'].

πŸ“¦ Output on screen:

['Name', 'Age']
['Ravi', '22']
['Amit', '20']

✍️ Writing to a CSV File

import csv

with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age"])         # Header
    writer.writerow(["Ravi", 22])            # Row 1
    writer.writerow(["Tisha", 20])           # Row 2

βœ… Explanation:

  • open(..., 'w') β†’ Write mode (overwrites the file if it exists).

  • newline='' β†’ Prevents blank lines between rows (especially on Windows).

  • writerow([...]) β†’ Writes a single row of data.

πŸ”Ž What’s inside output.csv now?

Name,Age
Ravi,22
Amit,20

πŸ“Œ Real-Life Use Cases for CSV:

  • Storing student marks or attendance.

  • Exporting product lists from a shop.

  • Downloading data from a website or app in table form.


βœ… What is JSON?

  • JSON is like a dictionary in Python.

  • It stores data as key-value pairs (just like contacts in your phone: name β†’ number).

  • It’s widely used in web development, APIs, and data sharing between apps.


✍️ Saving (Writing) JSON Data

import json

person = {"name": "Alice", "age": 25}

with open("data.json", "w") as f:
    json.dump(person, f)

βœ… Explanation:

  • json.dump(...) converts Python data into JSON format and saves it in a file.

  • The file data.json will look like this:

{"name": "Alice", "age": 25}

πŸ“– Reading JSON Data

import json

with open("data.json") as f:
    data = json.load(f)
    print(data)
{'name': 'Alice', 'age': 25}
  • json.load(...) reads the JSON file and converts it back to a Python dictionary.


πŸ“Œ Real-Life Use Cases for JSON:

  • Storing user settings (like dark mode on/off).

  • Handling API data from websites (like weather, news, etc.).

  • Saving configuration data in applications.


🧠 When to Use What?

Feature

CSV

JSON

Structure

Rows and columns (tabular)

Nested data (like a dictionary)

Best For

Simple tables (e.g., marks)

Structured data (e.g., user info)

Human-readable

βœ… Yes

βœ… Yes

Supported By Excel

βœ… Yes

❌ Not directly

Use in APIs

❌ No

βœ… Yes


🧠 Summary:

  • Use CSV when data looks like a table.

  • Use JSON when data looks like key-value pairs or nested objects.

  • Always use with open(...) β€” it's safer and auto-closes the file!