← Back to Chapters

Python Read Files

? Python Read Files

? Quick Overview

Reading files in Python is essential for working with data stored in text or binary files. Python provides simple, powerful tools to open a file, read its contents, and process lines efficiently using different methods like read(), readline(), readlines(), and direct iteration over the file object.

? Key Concepts

  • File path: Location of the file you want to read (e.g., "example.txt").
  • Mode: Use "r" for reading text files.
  • File object: The value returned by open() that you use to read data.
  • Context manager: with open(...) as file: automatically closes the file.
  • Newline characters: Each line in a text file usually ends with \n.
  • Memory usage: Choose the right method depending on file size (full read vs line by line).

? Syntax & Theory

Basic pattern for reading a text file in Python using a context manager:

? General File-Reading Pattern
with open("example.txt", "r") as file:
    # Work with the file object here
    data = file.read()
    print(data)

The with statement makes sure the file is properly closed after its block of code is executed, even if an error occurs. Inside the block, you can choose different reading methods based on your needs.

? Code Examples

? Using read()

read() reads the entire file content as a single string. This is convenient for small to medium files where loading everything into memory is safe.

? View read() Example
with open("example.txt", "r") as file:
    # Open the file in read mode
    content = file.read()
# Print the full file content
print(content)

? Using readline()

readline() reads one line at a time. It is useful for large files where reading all content at once is not efficient.

? View readline() Example
with open("example.txt", "r") as file:
    # Read lines one by one using readline()
    line1 = file.readline()
    line2 = file.readline()
    # Print the first two lines
    print(line1, line2)

? Using readlines()

readlines() reads all lines into a list where each element represents one line from the file.

? View readlines() Example
with open("example.txt", "r") as file:
    # Read all lines into a list
    lines = file.readlines()
    # Loop through and process each line
    for line in lines:
        print(line.strip())

? Iterating Over the File Object

You can iterate directly over the file object line by line, which is both clean and memory efficient.

? View Iteration Example
with open("example.txt", "r") as file:
    # Iterate directly over the file object
    for line in file:
        print(line.strip())

?️ Common Use Cases

  • Processing log files line by line.
  • Reading configuration files or settings.
  • Loading simple datasets from .txt or .csv files.
  • Parsing reports, exports, or generated text files.

? Output & Explanation

? What the Output Looks Like

Suppose example.txt contains:

Hello, Python!
This is a file read demo.

Using read() will print the entire content exactly as it appears in the file.
Using readline() twice will first print the first line, then the second line.
Using readlines() or iterating over the file will allow you to handle one line at a time, so you can strip whitespace, search for keywords, or transform each line before printing.

? Tips & Best Practices

  • Use with blocks to ensure files are automatically closed after use.
  • Use readline() or iteration for very large files to avoid loading everything into memory.
  • Call strip() on each line to remove newline characters and extra spaces.
  • Be mindful of file encoding (e.g., encoding="utf-8") when reading non-ASCII text.

? Try It Yourself

  • Read a file and print only the lines that contain a specific keyword (e.g., "error").
  • Count and print the number of lines in a text file.
  • Read a file and print its lines in reverse order.