Showing posts with label read write files Python. Show all posts
Showing posts with label read write files Python. 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.


Lesson 8: File Handling and Exception Handling | Coding Class Series

March 16, 2026 0



Lesson 8: File Handling and Exception Handling | Coding Class Series

Introduction

Welcome to Lesson 8!
In this lesson, we will learn about file handling in Python and how to manage errors using exception handling. These skills are essential to make your programs robust and data-driven.


1. File Handling

File handling allows your program to read from and write to files on your computer.

Opening a file:

file = open("example.txt", "w")  # 'w' mode to write
file.write("Hello, Python!")
file.close()

Reading a file:

file = open("example.txt", "r")  # 'r' mode to read
content = file.read()
print(content)  # Output: Hello, Python!
file.close()

Using with statement (recommended):

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

File Modes:

  • r → read
  • w → write (overwrite)
  • a → append
  • rb / wb → read/write binary

2. Exception Handling

Exceptions occur when your program runs into an error.
Python allows you to handle exceptions gracefully using try, except, finally blocks.

Example:

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Enter a number.")
finally:
    print("Execution completed.")

Key Points:

  • try: Block where error might occur
  • except: Handles specific errors
  • finally: Executes always, even if an error occurs

3. Combining File Handling and Exceptions

You can handle file errors with exception handling:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file name!")

Benefits:

  • Prevents program crashes
  • Provides useful error messages
  • Improves program reliability

4. Practice Exercises

  1. Create a file notes.txt and write 5 lines of text in it.
  2. Read the file and count the number of words.
  3. Write a program that asks the user for a filename and prints its content. Handle errors if the file does not exist.
  4. Create a program that divides two numbers and handles division by zero and invalid input using exception handling.