KAHIBARO Bookshelves
Discord Login Register

10.2. 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:

  • 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:

  1. Open the file
  2. Read its contents
  3. 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 done

Key points:

  • If you omit the mode, open("example.txt") is the same as open("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:

  • file is your file object (you can choose the name).
  • You can call methods like read(), readline(), readlines(), or loop over file.

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 line you get includes the newline character \n at the end (unless it’s the very last line without a newline).
  • Printing line directly may produce blank-looking lines because print() 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 string
  • readline() → one line at a time (each call)
  • readlines() → list of all lines
  • for 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
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

  • 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms