Showing posts with label Python file handling. Show all posts
Showing posts with label Python file handling. Show all posts

Monday, March 16, 2026

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

March 16, 2026 0



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

Introduction

Welcome to Lesson 20!
In this lesson, we will learn file handling in Python, including reading, writing, appending, and advanced I/O operations.
File handling is essential to store and retrieve data for programs.


1. Opening a File

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

Syntax:

file = open("filename.txt", "mode")

Modes:

  • "r" – Read (default)
  • "w" – Write (creates new file or overwrites)
  • "a" – Append (adds content at the end)
  • "r+" – Read and Write

Example:

file = open("sample.txt", "w")
file.write("Hello, World!")
file.close()

2. Reading from a File

file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

Other reading methods:

  • readline() – reads one line at a time
  • readlines() – reads all lines into a list
file = open("sample.txt", "r")
print(file.readline())
print(file.readlines())
file.close()

3. Writing and Appending

  • Writing overwrites the file:
file = open("sample.txt", "w")
file.write("New content here.")
file.close()
  • Appending adds data to the end:
file = open("sample.txt", "a")
file.write("\nThis line is appended.")
file.close()

4. Using with Statement

The with statement automatically closes the file:

with open("sample.txt", "r") as file:
    content = file.read()
    print(content)
with open("sample.txt", "a") as file:
    file.write("\nAdding new line safely.")

5. Advanced I/O

  • Binary files"rb" and "wb" modes for reading/writing binary files.
  • File positioningseek() and tell() methods.
with open("sample.txt", "r") as file:
    print(file.tell())  # Current position
    print(file.read(5)) # Read 5 characters
    file.seek(0)        # Move pointer to start
  • Checking file existence using os module:
import os
if os.path.exists("sample.txt"):
    print("File exists")
else:
    print("File does not exist")

6. Practice Exercises

  1. Create a text file and write 5 lines of your choice.
  2. Read the file and print each line one by one.
  3. Append 3 more lines to the same file.
  4. Use seek() and tell() to read specific parts of the file.
  5. Try opening a file in binary mode and read/write some data.


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 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.


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.