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(), andreadlines(). - 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
- Manually create a file named
poem.txtin your folder and write 3 lines of text in it. - Write a Python script that uses
with open(...)to read the file. - Print each line with its length (character count) next to it.
- Example:
Line 1: Hello World (11 characters)
- Example:
Quick Knowledge Check
- What does the
"r"stand for inopen("file.txt", "r")? - What is the main difference between
read()andreadlines()? - Why is the
withkeyword considered "best practice"? - 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
withstatement 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!