Table of Contents
Why Reading Text Files Matters
Reading text files is one of the most common things you’ll do with Python. Logs, configuration files, CSV data, plain notes, and many other formats are just text.
In this chapter, you’ll learn how to:
- Open a text file for reading
- Read its contents in different ways
- Loop over lines in a file
- Handle newlines and whitespace
- Close files safely using
with
This chapter focuses specifically on reading text files, not writing them.
Opening a File for Reading
To read a file, you usually follow this pattern:
- Open the file
- Read its contents
- Close the file (or let Python close it for you)
The basic function is open():
open(file, mode)- For reading text, the most common mode is
"r"(read).
Example (not the recommended final style yet):
file = open("example.txt", "r") # open file for reading
content = file.read() # read all text
print(content)
file.close() # close when you're doneKey points:
- If you omit the mode,
open("example.txt")is the same asopen("example.txt", "r")(read text). - If the file does not exist, opening in
"r"mode causes an error.
You’ll learn better, safer patterns next.
Using `with` for Safe File Reading
The best and safest way to work with files in Python is using a with block. This automatically closes the file for you, even if an error happens.
with open("example.txt", "r") as file:
content = file.read()
print(content)
# After this block, the file is automatically closed
Inside the with block:
fileis your file object (you can choose the name).- You can call methods like
read(),readline(),readlines(), or loop overfile.
Outside the with block, you should not use file anymore; it’s already closed.
Reading the Whole File at Once: `read()`
read() returns the entire file as one single string.
with open("example.txt", "r") as file:
content = file.read()
print("File content:")
print(content)This is useful when:
- The file is small
- You want to process all text as one string
Be careful with very large files: read() loads everything into memory at once.
You can also give read() a number of characters to read:
with open("example.txt", "r") as file:
first_10_chars = file.read(10)
print(first_10_chars)Reading Line by Line with a `for` Loop
Files are naturally divided into lines, and Python makes it easy to process them one at a time.
The most common pattern for reading files is:
with open("example.txt", "r") as file:
for line in file:
print(line)This loops over each line in the file.
Important details:
- Each
lineyou get includes the newline character\nat the end (unless it’s the very last line without a newline). - Printing
linedirectly may produce blank-looking lines becauseprint()adds its own newline.
To avoid double newlines, you can strip them:
with open("example.txt", "r") as file:
for line in file:
line = line.rstrip("\n") # remove trailing newline
print(line)
You’ll often see rstrip() or strip() used when processing lines.
Reading a Single Line: `readline()`
readline() reads one line from the file each time you call it.
with open("example.txt", "r") as file:
first_line = file.readline()
print("First line:", first_line)
second_line = file.readline()
print("Second line:", second_line)
When there are no more lines, readline() returns an empty string "".
This gives you more manual control but is less common than looping with for line in file.
Reading All Lines Into a List: `readlines()`
readlines() reads all lines and returns a list of strings, one per line.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)Example output:
['First line\n', 'Second line\n', 'Third line\n']Each element in the list includes the newline character at the end (if present).
You can loop over this list later:
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.rstrip("\n"))Comparing the main methods:
read()→ one big stringreadline()→ one line at a time (each call)readlines()→ list of all linesfor line in file→ recommended for processing large files line by line
Handling Newlines and Whitespace
When reading text files, you’ll constantly deal with:
- Newlines:
\n - Extra spaces or tabs
Common techniques:
Removing the newline only
line = line.rstrip("\n")Removing surrounding whitespace (spaces, tabs, newlines)
line = line.strip()This is useful when:
- Reading data values from a file
- Comparing text
- Parsing simple file formats (like
key = value)
Example:
with open("data.txt", "r") as file:
for line in file:
clean = line.strip()
if clean: # skip empty lines
print("Line:", clean)Reading Files with a Specific Encoding (Basic)
Text files are stored using an encoding (for example, UTF-8). Most modern text files use UTF-8, and Python uses UTF-8 by default in many environments, but not always.
You can specify the encoding explicitly:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)You might need this if:
- You see strange characters when reading a file
- You know the file uses a specific encoding (e.g.,
"utf-8","latin-1")
For most beginner use cases, encoding="utf-8" is a good choice.
Reading Files Safely: Common Issues
File not found
If the file doesn’t exist in the expected location, you’ll get an error like:
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
Typical causes:
- Wrong file name (typo)
- File is in a different folder than your script
- You’re running the script from a different working directory
Basic example with simple error handling:
filename = "example.txt"
try:
with open(filename, "r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file", filename, "was not found.")(You’ll learn more about error handling in the errors and debugging chapter.)
Forgetting to close the file
If you don’t use with, you must call close() manually:
file = open("example.txt", "r")
content = file.read()
file.close()
If you forget close(), the file may stay open longer than needed. Using with is the recommended way to avoid this problem.
Basic Line Processing Examples
Here are a few common patterns you’ll use when reading text files.
Counting lines in a file
line_count = 0
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
line_count += 1
print("Number of lines:", line_count)Searching for a word in a file
word_to_find = "Python"
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
if word_to_find in line:
print("Found:", line.rstrip("\n"))Reading numbers from a file and summing them
Suppose numbers.txt looks like this:
10
20
30
40You can read and sum the numbers:
total = 0
with open("numbers.txt", "r", encoding="utf-8") as file:
for line in file:
line = line.strip()
if line: # skip empty lines
number = int(line) # convert text to int
total += number
print("Total:", total)This combines reading text with converting strings to numbers.
Summary of Key Patterns
- Use
with open("file.txt", "r") as file:for safe reading. file.read()→ one string with the whole file.file.readline()→ one line each time you call it.file.readlines()→ list of all lines.for line in file:→ recommended for processing each line.- Use
.strip()or.rstrip("\n")to clean up lines. - Use
encoding="utf-8"when you need to control text encoding.
These patterns are the foundation of reading text files in Python. You’ll use them again when building simple file-based programs and automation scripts.