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

Monday, March 16, 2026

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.