MSIT

Close the file

Every open needs a close. If the function returns before close, the file can stay open.

A with statement closes the file when the block ends, including when you return from inside it.

Why the close can be skipped

A function stops at return. Any line after that return does not run. If close is written after return, it never runs, and the file can stay open.

with fixes that order problem. You open the file in the with line. The indented block is the only place you use the handle. When the block ends, Python closes the file for you. That includes a return inside the block.

The Input and output tutorial calls this good practice. The file is closed after the suite finishes, even if an exception is raised. You do not write a try and a finally to get that.

A worked example

note.txt still contains Hello. This function reads it and returns the text. The with line both opens the file and names the handle.

  1. Open note.txt with with and encoding="utf-8".
  2. Call read on the handle inside the block.
  3. Return that string. Do not call close yourself.

The name after as is the handle. handle.read() is the text. For this file, the return value is "Hello". When return leaves the block, the file is already being closed. You do not need a close line after the with.

It is good practice to use the with keyword when dealing with file objects.

— Python tutorial, Reading and writing files

Indentation marks the block. The return must be indented under the with. If it sits at the same level as with, it is outside the block, and you may be using the handle after it has been closed.

  • The header opens the file and binds the handle.
  • The body reads, and may return.
  • The end of the body closes the file, even on a return.

Indent the read and the return under the with line.

Match the word with what it does.

  • open
  • read
  • close

When does a with statement close the file?

Exercise

Write a function named message that reads note.txt with a with statement and returns the text.

Write a function named message that reads note.txt with a with statement and returns the text.

Output