Module 5 Lesson 1: Reading Text Files
·Programming

Module 5 Lesson 1: Reading Text Files

Give your data a permanent home. Learn how to open, read, and process information from text files using Python's built-in tools.

Module 5 Lesson 1: Reading Text Files

Until now, whenever we closed our Python program, all our variables, lists, and objects vanished into thin air. To build real apps, we need to save data to the hard drive. In this module, we start our journey into File Handling.

Lesson Overview

In this lesson, we will cover:

  • The open() Function: Your key to the file system.
  • Reading Modes: Understanding 'r' (read).
  • Methods of Reading: read(), readline(), and readlines().
  • The Importance of Closing Files: Why leaving files open is bad.

1. Opening a File

To work with a file, you first need to "open" it. Python provides the open() function for this.

# General Syntax: file_object = open("filename", "mode")
file = open("example.txt", "r") # 'r' stands for read mode

2. Three Ways to Read

Once a file is open, you have several ways to get the data out.

A. read() - All at once

Perfect for small files where you want everything in one big string.

content = file.read()
print(content)

B. readline() - Line by line

Reads just one line at a time. Great for processing huge files without crashing your computer.

line1 = file.readline()
print(line1)

C. readlines() - As a list

Turns every line into an item in a Python list.

lines = file.readlines()
for line in lines:
    print(line.strip()) # .strip() removes the hidden newline character \n

3. Don't Forget to Close!

Files are like books; if you leave too many open on your desk, you run out of space. In programming, leaving files open can cause memory leaks and prevent other programs from using the file.

file = open("data.txt", "r")
# ... do work ...
file.close() # CRITICAL STEP

4. The Modern Way: Context Managers

Manually closing files is easy to forget. Python provides a "Context Manager" using the with keyword that closes the file automatically for you, even if your code crashes!

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

# No need to call file.close()! It's handled.

Practice Exercise: The Poem Reader

  1. Manually create a file named poem.txt in your folder and write 3 lines of text in it.
  2. Write a Python script that uses with open(...) to read the file.
  3. Print each line with its length (character count) next to it.
    • Example: Line 1: Hello World (11 characters)

Quick Knowledge Check

  1. What does the "r" stand for in open("file.txt", "r")?
  2. What is the main difference between read() and readlines()?
  3. Why is the with keyword considered "best practice"?
  4. What happens if you try to open a file that doesn't exist in "r" mode?

Key Takeaways

  • open() is used to access files on your computer.
  • Always specify a mode ('r' for reading).
  • Use strip() to clean up extra spaces and newlines from file data.
  • Always use the with statement to ensure your files are closed safely.

What’s Next?

Reading is only half the battle. In Lesson 2, we’ll learn how to write our own data into files and append to existing ones!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn