CodeBlanks Logo Icon CodeBlanks

with statement

Learn automatic close with with open(...) as f:.

The with statement closes automatically

Forgetting to call close() after opening a file is a common bug. The with statement solves this: when the block ends, the file is closed automatically. Write with open("f.txt", encoding="utf-8") as f: and the file object f is usable inside the block; it closes on exit.

Even if an error occurs, with still closes the file. That's why with is always recommended for file work. The code is shorter and safer.

Practice Write and read with with

Use two with blocks. In the first, open the file for writing: with open("hi.txt", "w", encoding="utf-8") as f: and inside the block write f.write("Hello"). In the second, open in read mode: with open("hi.txt", "r", encoding="utf-8") as f: and inside the block write print(f.read()). Do not call close().

Starter code

main.py
# with: write Hello to the file
# with: read the file and print

Sample solution

main.py
# with: write Hello to the file
with open("hi.txt", "w", encoding="utf-8") as f:
    f.write("Hello")
# with: read the file and print
with open("hi.txt", "r", encoding="utf-8") as f:
    print(f.read())

Expected output

Hello

Multiple files in one with

You can open several files side by side in the same with: with open("a.txt") as fa, open("b.txt") as fb:. Both close at the end of the block.

Since Python 3.10 a parenthesized multi-line form exists: with (open("a.txt") as fa, open("b.txt") as fb):. This form is more readable and great for splitting long lines.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main benefit of using with?

  • The file closes automatically at block exit Correct answer
  • The file size shrinks
  • The operation uses less memory
  • The file opens faster

Explanation: with closes the file automatically when the block exits; safe even on errors.

2 Match the with statement

Term Meaning
with Automatic closing
as Binding name
open File opening
close Manual closing

3 Complete the with statement

Question
____ open("f.txt", encoding="utf-8") as f:
    print(f.read())
Answer
with open("f.txt", encoding="utf-8") as f:
    print(f.read())

Explanation: The with statement closes the file automatically.

All lessons in Intermediate