Lesson 37 of 60
โฎPrev Nextโฏ

PY-101 ยท Files and errors

with and context managers

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

37of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A with statement runs a block of code inside a context manager, which sets something up at the start and always cleans it up at the end, even if an error happens. with open(...) as f: closes the file for you. The same pattern is used for database connections, locks and timers.

    • Use with for files
    • Know why cleanup matters
    • Write a tiny context manager

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    with and context managers, running
    1. from contextlib import contextmanager
    2. with open("log.txt", "w") as f:
    3. f.write("started\n")
    4. print("Inside, closed?", f.closed)
    5. print("After, closed?", f.closed)
    6. @contextmanager
    7. def step(name):
    8. print("Start", name)
    9. yield
    10. print("Done", name)
    11. with step("backup"):
    12. print("Copying files...")
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA script opens 500 files and forgets to close them. Around file 250 the computer refuses to open any more. with makes "forgot to close" impossible.
    2. The Python ideawith something() as name:A with statement runs a block of code inside a context manager, which sets something up at the start and always cleans it up at the end, even if an error happens.
    3. In real lifeDatabase libraries use with to make sure a transaction is committed when all goes well and rolled back when something fails.

    Start with a question

    A script opens 500 files and forgets to close them. Around file 250 the computer refuses to open any more. with makes "forgot to close" impossible.

    Leaked files, connections and locks are classic production bugs. with prevents them by design.

    Explain it like I'm 10

    with is like a library that checks books back in for you the moment you leave the reading room, even if you rush out.

    The technical explanation

    When the with block ends (normally or by an exception) the context manager's cleanup runs.

    f.closed is False inside the block and True afterwards.

    With contextlib.contextmanager, code before yield is the setup and code after it is the cleanup.

    Syntax

    with something() as name:
        ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Database libraries use with to make sure a transaction is committed when all goes well and rolled back when something fails.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does with open(...) do at the end of the block?
    2. 2. Does cleanup still run if an error happens inside with?
    3. 3. In a @contextmanager function, what separates setup from cleanup?
    4. 4. Do you need f.close() inside a with open block?
    5. 5. Which is also commonly used with with?

    Questions people ask

    Why use with open instead of open and close?

    with closes the file even if an error happens halfway, and it is shorter. Forgetting close() leaks files.

    Can I open two files in one with statement?

    Yes: with open("in.txt") as src, open("out.txt", "w") as dst:.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Why use with open instead of open and close?

    with closes the file even if an error happens halfway, and it is shorter. Forgetting close() leaks files.

    beginner Can I open two files in one with statement?

    Yes: with open("in.txt") as src, open("out.txt", "w") as dst:.

    intermediate What does with open(...) do at the end of the block?

    Closes the file. The file is closed automatically.

    intermediate Does cleanup still run if an error happens inside with?

    Yes. That is the whole point.

    Quick revision

    Remember

    • Use with for files
    • Know why cleanup matters
    • Write a tiny context manager
    • You do not need f.close() inside a with block. It happens automatically when the block ends.

    Syntax

    with something() as name:
        ...

    Official documentation