Showing posts with label Python CSV. Show all posts
Showing posts with label Python CSV. Show all posts

Monday, March 16, 2026

Lesson 14: Python File Handling and CSV/JSON | Coding Class Series

March 16, 2026 0



Lesson 14: Python File Handling and CSV/JSON | Coding Class Series

Introduction

Welcome to Lesson 14!
In this lesson, we will learn how to work with files in Python, including reading, writing, and updating text files, as well as working with CSV and JSON formats.
File handling is essential for storing data permanently and exchanging it between programs.


1. Opening and Closing Files

Use the open() function to open a file. Always close it after use.

# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()

# Open the file in read mode
file = open("example.txt", "r")
print(file.read())  # Hello, Python!
file.close()

2. Using with Statement

with automatically closes the file after usage.

with open("example.txt", "w") as f:
    f.write("Using with statement!")

with open("example.txt", "r") as f:
    print(f.read())  # Using with statement!

3. Reading Files

  • read(): reads the entire file
  • readline(): reads one line at a time
  • readlines(): reads all lines into a list
with open("example.txt", "r") as f:
    print(f.readline())
    print(f.readlines())

4. Writing and Appending Files

  • "w" mode: write (overwrites existing content)
  • "a" mode: append (adds new content)
with open("example.txt", "a") as f:
    f.write("\nAppending a new line!")

with open("example.txt", "r") as f:
    print(f.read())

5. Working with CSV Files

CSV (Comma Separated Values) files store tabular data.

import csv

# Writing to a CSV file
with open("students.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Alice", 14, "A"])
    writer.writerow(["Bob", 15, "B"])

# Reading from a CSV file
with open("students.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

6. Working with JSON Files

JSON is widely used for data exchange between applications.

import json

# Writing JSON to a file
data = {
    "name": "Alice",
    "age": 14,
    "subjects": ["Math", "English", "Science"]
}

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

# Reading JSON from a file
with open("data.json", "r") as jsonfile:
    loaded_data = json.load(jsonfile)
    print(loaded_data["name"])  # Alice

7. Practice Exercises

  1. Create a text file notes.txt and write 5 of your favorite quotes.
  2. Create a CSV file inventory.csv for a shop with columns: Item, Quantity, Price. Read it and calculate total value.
  3. Create a JSON file with your friends' details (name, age, city) and load it back in Python.
  4. Read a text file and count the number of words in it.


Lesson 11: Python File Handling and I/O | Coding Class Series

March 16, 2026 0

 


Lesson 11: Python File Handling and I/O | Coding Class Series

Introduction

Welcome to Lesson 11!
In this lesson, we will learn how to work with files in Python, including reading, writing, and appending data. File handling is crucial for data storage, logs, and application input/output.


1. Opening a File

Use the built-in open() function to open a file:

# Open a file in read mode
file = open("example.txt", "r")
print(file.read())
file.close()

Modes of File:

  • "r" → Read (default)
  • "w" → Write (creates or overwrites)
  • "a" → Append (adds data at end)
  • "rb" / "wb" → Read/Write in binary mode

2. Reading Files

  • Read all content at once:
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • Read line by line:
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
  • Read specific characters:
with open("example.txt", "r") as file:
    print(file.read(10))  # Reads first 10 characters

3. Writing to Files

  • Write new content (overwrites existing file):
with open("example.txt", "w") as file:
    file.write("Hello, Python File Handling!")
  • Append content to existing file:
with open("example.txt", "a") as file:
    file.write("\nThis is appended text.")

4. Using with Statement

The with statement automatically closes the file, even if an error occurs:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)
# File is automatically closed here

5. Handling CSV Files

Python provides csv module to handle CSV files:

import csv

# Writing to a CSV
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "New York"])
    writer.writerow(["Bob", 30, "London"])

# Reading from a CSV
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

6. Practice Exercises

  1. Create a text file and write your favorite poem into it.
  2. Read the text file line by line and print lines containing the word "Python".
  3. Create a CSV file for your friends' names, age, and city, and read it using Python.
  4. Append new data to the existing CSV file and verify it.