Python
file handling
open with statement
programming tutorial
code examples

How to open a file using the open with statement

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, the normal way to open a file is with open(...) inside a with statement. The with block ensures the file is closed automatically when you are done, even if an exception happens inside the block. That makes it safer and cleaner than opening a file manually and remembering to close it later.

Basic Read Example

To read a text file:

python
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

This does three useful things at once:

  • opens the file
  • gives you a file object as f
  • closes the file automatically when the block ends

That automatic cleanup is the main reason with open(...) is the recommended pattern.

Writing to a File

The same pattern works for writing.

python
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, world!\n")

Mode matters:

  • '"r" for reading'
  • '"w" for writing and truncating'
  • '"a" for appending'
  • '"b" for binary mode, combined with others such as "rb" or "wb"'

Reading Line by Line

If you want to process a file incrementally, iterate over the file object.

python
with open("example.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

This is often better than read() for large files because it avoids loading the whole file into memory at once.

Binary Files

For binary data, open the file in binary mode and do not pass a text encoding.

python
with open("image.png", "rb") as f:
    header = f.read(8)
    print(header)

The file object then works with bytes instead of text strings.

Why with Is Better Than Manual Close

You can open a file without with, but then you take responsibility for closing it yourself.

python
1f = open("example.txt", "r", encoding="utf-8")
2try:
3    print(f.read())
4finally:
5    f.close()

This works, but with is shorter, clearer, and harder to get wrong.

The real value is reliability. Even if code inside the block raises an exception, the file still gets closed properly.

Multiple Files in One Statement

Python also lets you open more than one file in a single with statement.

python
with open("input.txt", "r", encoding="utf-8") as src, \
     open("copy.txt", "w", encoding="utf-8") as dst:
    dst.write(src.read())

This is useful when copying, transforming, or comparing files.

Why This Helps With Exceptions

The with statement matters most when something goes wrong. If an exception is raised inside the block, Python still closes the file as the context manager exits.

python
with open("example.txt", "r", encoding="utf-8") as f:
    first_line = f.readline()
    raise RuntimeError("something failed after opening the file")

Even though the block exits through an exception, the file handle is not left hanging open. That automatic cleanup is the real reason with open(...) is the default recommendation rather than only a stylistic preference.

Common Pitfalls

The most common mistake is omitting the encoding argument for text files when consistent text handling matters.

Another issue is using "w" when you really wanted "a", which silently truncates the existing file.

Developers also sometimes use read() on very large files when line-by-line iteration would be more memory-friendly.

Finally, do not use text mode for binary files. If the content is binary, open it with "rb" or "wb".

Summary

  • Use with open(...) as f: as the standard Python file-opening pattern.
  • The with block closes the file automatically, even on exceptions.
  • Choose the correct mode such as "r", "w", "a", or binary variants.
  • Specify an encoding for text files when appropriate.
  • Prefer line-by-line iteration for large text files and binary mode for non-text data.

Course illustration
Course illustration

All Rights Reserved.