CodeBlanks Logo Icon CodeBlanks

with statement

Learn how the with statement works.

The with statement

The with statement opens a resource, uses it and closes it automatically. No matter how the block ends — even on error — cleanup always runs:

with open("dosya.txt") as f:
    icerik = f.read()
# f auto-closed

Here open opens the file; when the with block ends the file closes automatically. No need to write finally. This prevents resource leaks.

It is standard for resources like files, database connections and locks.

Naming the resource with as

The with ... as pattern gives the resource a name. This name is used inside the block:

with open("dosya.txt") as f:
    print(f.read())

Here f holds the file object. When the block ends f closes automatically; no need to call f.close().

This is the most common pattern for file operations.

Practice Use a simple context manager

The Kaynak class is already defined. Inside a with Kaynak(): block write print("içeride").

Starter code

main.py
class Kaynak:
    def __enter__(self):
        print("açtı")
        return self
    def __exit__(self, *args):
        print("kapattı")

# open a with block and print içeride

Sample solution

main.py
with Kaynak():
    print("içeride")

Expected output

açtı
içeride
kapattı

Questions and answers

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

1 What does the with block guarantee?

  • The code runs faster
  • No error is raised
  • The resource is always closed Correct answer
  • Variables are deleted

Explanation: The with block closes the resource even on error.

2 Complete the with statement

Question
____ Kaynak():
    print("içeride")
Answer
with Kaynak():
    print("içeride")

Explanation: with Kaynak() starts a context manager.

3 Match with concepts

Term Meaning
with Starts the block
as Names the resource
__enter__ Opening
__exit__ Closing

All lessons in Intermediate