Repaso
Español
PythonCorePY-56

Why is with open("data.txt") as f: preferred over f = open("data.txt")?

Options

  1. It reads the file faster than a plain open() call does
  2. The file closes by itself when the block ends, even after an error (Correct option)
  3. It creates the file for you when it does not exist yet
  4. It loads the whole file into memory in a single step

Answer

The file is closed automatically when the block ends, even if an error happens

Why

An open file uses operating-system resources and must be closed.

With with, Python closes the file for you as soon as the indented block ends, also if an exception happens in the middle.

This pattern is called a context manager; it is also used for locks and database connections.

Remember

Use with for anything that must be closed or released.

Key terms

Practice this question in Repaso