Beginner   Chapter 102 · 22 min read · Module 8: File Handling

with Statement

Learning objectives
  • After this chapter you can open and close files safely with the with statement.
  • You can explain why a file should always be closed and what can go wrong if it is not.
  • You can open two files in one with statement and copy data between them.
  • You can check a file's closed attribute and understand what happens after the block ends.
  • You can describe in simple words what a context manager does.

When a program opens a file, the operating system gives it a small resource. That resource must be given back by closing the file. If you forget, data you wrote may stay in a buffer and never reach the disk, and a program that opens many files can run out of handles.

The with statement solves this problem. It opens the file, lets you work with it inside an indented block, and then closes it automatically. This happens even when an error stops your code half way. Because of this, with is the standard way to handle files in modern Python.

In this chapter you will see the problem that with solves, learn its syntax, and use it with one file and with several files. You will also get a first look at how it works behind the scenes.

Why closing a file matters

A file object keeps a small buffer in memory. When you call write(), the text may wait in that buffer for a while. Calling close() flushes the buffer, which means the text is pushed to the disk, and then it releases the file. If you never close the file, your data may be incomplete, and on some systems other programs cannot open the file until yours ends.

The old way is to call close() yourself. This works, but it is easy to forget. Even worse, if an error happens between open() and close(), the close line is never reached. The file stays open until the program ends.

Example 1: Closing by hand
f = open("notes.txt", "w")
f.write("first line\n")
f.close()
print(f.closed)
True

Here the file is closed correctly and f.closed is True. But look at how much depends on you: you must remember the last line, and nothing protects you from an error before it.

The with statement

with statement: a statement that sets something up, runs an indented block, and then cleans up automatically, even if the block raises an error

With files, the pattern is with open(name, mode) as variable:. The file object is stored in the variable after as. When the indented block ends, Python closes the file for you. You do not write close() at all.

Example 2: Write and read with with
with open("todo.txt", "w") as f:
    f.write("buy milk\n")
    f.write("call Asha\n")

print(f.closed)

with open("todo.txt", "r") as f:
    text = f.read()

print(text)
print(f.closed)
True buy milk call Asha True

Notice that the variable f still exists after the block, but the file it points to is closed. If you try f.read() after the block, Python raises ValueError: I/O operation on closed file. Always finish your work with the file inside the block. You may keep the data you read, such as text above, and use it later.

Safe even when errors happen

The real strength of with is that it cleans up even when something goes wrong. Think of it as a built-in try and finally. In the next example an error is raised inside the block. We catch it outside, and then check that the file was still closed.

Example 3: Closed even after an error
try:
    with open("data.txt", "w") as f:
        f.write("abc")
        value = int("not a number")
        f.write("never written")
except ValueError:
    print("error caught")

print(f.closed)
with open("data.txt") as g:
    print(g.read())
error caught True abc

The text abc was written before the error, and the file was closed properly, so the text reached the disk. Without with, the file would have stayed open.

More than one file at once

You can open several files in a single with statement by separating them with commas. All of them are closed when the block ends. This is very handy for copying or transforming data from one file to another.

Example 4: Copy lines to a new file
with open("source.txt", "w") as s:
    s.write("red\ngreen\nblue\n")

with open("source.txt") as src, open("copy.txt", "w") as dst:
    for line in src:
        dst.write(line.upper())

with open("copy.txt") as f:
    print(f.read(), end="")
print(src.closed, dst.closed)
RED GREEN BLUE True True

Python 3.10 and newer also allow the several open() calls to sit inside round brackets, spread over many lines. The comma style shown above works in every version.

A first look at context managers

The object that works with with is called a context manager. It has two special methods. __enter__ runs when the block starts and gives back the value stored after as. __exit__ runs when the block ends, whether normally or because of an error. For files, __exit__ calls close(). Many other things in Python are context managers too, such as locks, database connections, and temporary directories.

Tip: keep the with block short. Read or write what you need, then leave the block. Heavy work on the data can happen after the file is already closed.

Python syntax

Syntax
with open("file.txt", "r") as f:
    data = f.read()
Syntax
with open("a.txt") as src, open("b.txt", "w") as dst:
    dst.write(src.read())

Real-world applications

  • Saving program results to a log or report file without leaking file handles.
  • Reading configuration files at program start.
  • Copying or converting files, such as changing text to upper case.
  • Using the same pattern for database connections, locks and temporary files.

Common mistakes

Mistake: Using the file variable after the with block has ended.
Fix: Do all reading and writing inside the block. Store the data you need in another variable first.
Mistake: Writing open() without with and forgetting to call close().
Fix: Use with open(...) as f every time, so closing is automatic.
Mistake: Forgetting the colon or the indentation after the with line.
Fix: End the with line with a colon and indent the whole block by four spaces.
Mistake: Thinking that the with statement creates a new scope for variables.
Fix: Variables made inside the block still exist after it. Only the file is closed.

Important tips

  • Make with open(...) your habit for every file.
  • Check f.closed when you are unsure whether a file is still open.
  • Use the comma form to open a source and a destination file together.

Key points summary

  • with closes the file automatically when the block ends.
  • Cleanup happens even if an error is raised inside the block.
  • The name after as holds the file object.
  • Several files can be opened in one with statement.
  • A file object that is closed cannot be read or written.

Exam and interview points

  • with is the recommended way to open files in Python.
  • with relies on __enter__ and __exit__ methods of a context manager.
  • The file is closed even when an exception happens inside the block.
  • The variable after as remains available after the block, but the file is closed.

Quick revision

  • with open(name, mode) as f: ... closes f automatically.
  • Do file work inside the indented block.
  • f.closed tells you if a file is closed.
  • Use commas to open several files in one with.

Frequently asked questions

Do I still need to call close() when I use with?

No. The with statement calls it for you. Calling it again is harmless but not needed.

What happens if I read from the file after the with block?

Python raises ValueError: I/O operation on closed file, because the file was closed at the end of the block.

Can with be used for things other than files?

Yes. Any object that is a context manager works, for example locks, database connections and temporary directories.

Is with slower than open and close?

No. The speed is the same for practical purposes. The gain is safety and shorter code.

Practise this chapter

16 practice questions Take the chapter quiz

Related chapters