Kahibaro
Discord Login Register

Reading text files

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:

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:

  1. Open the file
  2. Read its contents
  3. Close the file (or let Python close it for you)

The basic function is open():

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 done

Key points:

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:

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:

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:

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:

Handling Newlines and Whitespace

When reading text files, you’ll constantly deal with:

Common techniques:

Removing the newline only

line = line.rstrip("\n")

Removing surrounding whitespace (spaces, tabs, newlines)

line = line.strip()

This is useful when:

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:

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:

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
40

You 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

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.

Views: 19

Comments

Please login to add a comment.

Don't have an account? Register now!