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

The standard way to read a file in Python is with the built-in open() function used as a context manager via the 'with' statement, which guarantees the file is closed even if an error occurs.

with open('data.txt', 'r') as f:
    contents = f.read()

Steps

  1. Call open('data.txt', 'r') inside a 'with' block — 'r' means read mode (the default)
  2. Use f.read() to get the entire file as one string, f.readlines() for a list of lines, or iterate 'for line in f' to process line by line
  3. The file is automatically closed when the with block exits, even if an exception is raised inside it

How it works

The 'with' statement uses Python's context manager protocol: open() returns a file object with __enter__ and __exit__ methods, and __exit__ closes the file automatically when the block ends.

Things to watch for

  • For large files, iterate line by line instead of calling .read() or .readlines() to avoid loading the whole file into memory at once
  • Always specify encoding='utf-8' explicitly when reading text files to avoid platform-dependent default encoding issues

FAQ

Do I need to call f.close() manually?

Not if you use 'with open(...) as f' — it closes the file automatically. Manual open()/close() calls are error-prone if an exception happens before close() runs.

More Python articles