For this tutorial you can use a text editor such as notepad (on Windows) to create a text file to read.
Opening a File the Safe Way
The golden rule is to use a context manager (with ... as ...). It opens the file, lets you read from it, and automatically closes it when finished, even if something goes wrong.
try:
with open("shopping_list.txt", "r") as f:
text = f.read()
print(text)
except FileNotFoundError:
print("Oops — file not found.")
This is the cleanest and safest way to read a file.
Try this:
- Create a small file and read it.
- Change the filename to something that doesn’t exist to see the error.
Different Ways to Read
You can read the whole file, just one line, or loop over it.
# Whole file
with open("data.txt", "r") as f:
text = f.read()
print(text)
# First line only
with open("data.txt", "r") as f:
line = f.readline()
print(line)
# Line by line (best for big files)
with open("data.txt", "r") as f:
for line in f:
print(line.rstrip())
Try this:
- Count how many lines are in a file.
- Print only the lines containing the word LiddleBit.
Common Exceptions
When working with files, a few errors are common:
- FileNotFoundError: the file doesn’t exist.
- PermissionError: you don’t have access.
- IsADirectoryError: you gave a folder instead of a file.
These are normal and can be handled with try…except to keep your program from crashing.







