Showing posts with label Python JSON tutorial. Show all posts
Showing posts with label Python JSON tutorial. Show all posts

Monday, March 16, 2026

Lesson 17: Python File Handling and Working with CSV/JSON | Coding Class Series

March 16, 2026 0



Lesson 17: Python File Handling and Working with CSV/JSON | Coding Class Series

Introduction

Welcome to Lesson 17!
In this lesson, we will learn how to read and write files in Python and work with CSV and JSON data formats.
File handling is essential to store, retrieve, and process data in Python programs.


1. Working with Text Files

Python provides the open() function to work with files.

Modes:

  • 'r' – Read (default)
  • 'w' – Write (creates or overwrites file)
  • 'a' – Append (add to file)
  • 'r+' – Read and Write

Example: Writing and reading a text file

# Write to a file
with open("example.txt", "w") as f:
    f.write("Hello, Python File Handling!\n")
    f.write("This is Lesson 17.\n")

# Read from the file
with open("example.txt", "r") as f:
    content = f.read()
    print(content)

2. Reading Files Line by Line

with open("example.txt", "r") as f:
    for line in f:
        print(line.strip())

3. Appending Data to a File

with open("example.txt", "a") as f:
    f.write("Appending a new line.\n")

4. Working with CSV Files

Python provides the csv module to work with CSV data.

Writing CSV:

import csv

data = [["Name", "Age", "City"],
        ["Alice", 25, "New York"],
        ["Bob", 30, "London"]]

with open("people.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Reading CSV:

import csv

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

5. Working with JSON Files

Python provides the json module to work with JSON data.

Writing JSON:

import json

person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

with open("person.json", "w") as f:
    json.dump(person, f, indent=4)

Reading JSON:

import json

with open("person.json", "r") as f:
    data = json.load(f)
    print(data)

6. Practice Exercises

  1. Create a text file notes.txt, write multiple lines, and read them line by line.
  2. Create a CSV file for your favorite movies (Title, Director, Year) and read it back.
  3. Create a JSON file containing 3 student records with name, age, and grade. Read and display them in Python.
  4. Append new data to both CSV and JSON files.