3. With statement

The with statement runs an expression that opens a file and closes that file automatically when the block ends:

  • open("/tmp/demo.txt", "w") runs first and returns the file object.
  • as file binds that object to the name file for the block.
  • When the block ends, Python calls file.close() for you. You do not need to call it.
  • The name file still exists after the block, but the file is already closed.

Because closing happens at the end of the block, with also closes the file when an exception leaves the block. That is why it is the recommended way to work with files:

The closed attribute tells you whether a file object is closed: file.closed is False inside the block and True after it.

Coming from JavaScript? with is similar to a try/finally block that always calls close(), but written in one line.

#01

Write inside a with block

A with open(...) as file: block closes the file automatically when the block ends. You do not call close().

Open /tmp/with.txt in "w" mode with a with statement and write Welcome followed by a newline. Then print Saved. Do not call close().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Check that the file is closed

Inside the with block, file.closed is False. After the block ends, Python has closed the file, so file.closed is True.

Open /tmp/closed.txt in "w" mode with a with statement and write data. After the block, print file.closed. Do not call close().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Read inside a with block

with works for reading too: the file is closed as soon as the block ends.

Use one with block to write line one and line two as two lines to /tmp/with-read.txt. Then use a second with block to open it in "r" mode, call read(), and print the content without adding an extra newline (end=""). Do not call close().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Close the file even when the block fails

The with statement closes the file before an exception leaves the block.

Open /tmp/error.txt in "w" mode inside a with block, write data, and then raise ValueError("boom") inside the same block. Wrap the with statement in a try block and catch the ValueError. In the except block, print file.closed. Do not call close().

Print exactly:

Create a free account to save your progress and unlock chapter 2.