How to Read a File in Python

Read a file in Python using open() with the with statement, line by line or all at once, and why with automatically closes the file for you.

Published September 17, 2026

Open a file with a with-statement and call read(), readline() or iterate over it. The with block closes the file automatically, even when an error occurs.

The concept

open(path, mode, encoding) returns a file object. Mode 'r' reads text, 'rb' reads bytes. Always pass encoding='utf-8' for text so the result does not depend on the operating system.

For large files, loop over the file object line by line instead of read(), which loads everything into memory.

Open, read, close

  1. open('data.txt', encoding='utf-8') returns a file object
  2. read() / for line in f pulls the content
  3. The with block ends and Python closes the file for you

Practical examples

Read everything

with open('data.txt', encoding='utf-8') as f:
    text = f.read()

Line by line (memory-friendly)

with open('big.log', encoding='utf-8') as f:
    for line in f:
        if 'ERROR' in line:
            print(line.rstrip())

pathlib shortcut

from pathlib import Path
text = Path('data.txt').read_text(encoding='utf-8')

Handle a missing file

try:
    open('nope.txt').close()
except FileNotFoundError:
    print('file not found')

Common mistakes

  • Forgetting to close the file; use with.
  • Reading a multi-GB file with read().
  • Skipping encoding and getting UnicodeDecodeError on another machine.
  • Using a relative path that depends on where the script is launched.

Key takeaways

  • with open(...) as f is the standard pattern.
  • Iterate lines for large files.
  • Specify encoding='utf-8'.

FAQ

What is the difference between read, readline, readlines?

read returns one string, readline one line, readlines a list of all lines.

How do I read a CSV or JSON file?

Use the csv and json modules rather than parsing manually.

More Python articles