Python with Statement: as, Yielded Values and Multiple Context Managers
The Python with statement runs a block inside a context manager. With as, the block gets the value the manager yields. One with can hold several managers.
You need Python Context Managers, Python try finally and writing to a text file. The goal of this lesson: get a value from a context manager into its with block, and use several context managers in one with. Files are the main example.
Yield a value to as
@contextmanager runs your function up to yield. The value after yield is what with ... as name: stores in name. Here basket() yields a new, empty list.
from contextlib import contextmanager@contextmanagerdef basket(): items = [] yield items print("Checkout:", items)with basket() as cart: cart.append("apples") cart.append("bread")This prints Checkout: ['apples', 'bread']. cart and items are the same list, so the clean-up after yield sees what the block added.
Bare yield versus yield value: a bare yield gives the block nothing, so as stores None.
from contextlib import contextmanager@contextmanagerdef nothing_to_give(): yieldwith nothing_to_give() as thing: print(thing)This prints None. Calling a method on it fails: thing.append("apples") would raise AttributeError: 'NoneType' object has no attribute 'append'. If you see that error on a name from as, check what the context manager yields. open() works the same way: its as name gets the open file.
Open and close a file by hand
open() works without with. Store the file in a variable, write to it, then close it yourself with close(). A file's closed attribute tells you whether it is closed yet.
target = open("lesson-diary.txt", "w", encoding="utf-8")target.write("Day 1: found a key\n")with open("lesson-diary.txt", "r", encoding="utf-8") as source: print("Before close:", len(source.read()), "characters")target.close()print("Closed:", target.closed)with open("lesson-diary.txt", "r", encoding="utf-8") as source: print("After close:", source.read(), end="")It prints Before close: 0 characters, then Closed: True, then After close: Day 1: found a key. write() keeps short text in memory, and close() saves it to the file. That is why the file reads as empty before close(). source.read() gives the whole file as one string. write() adds no newline, so the text ends with \n, and end="" stops print() adding a second one.
This is what with open() does for you: it closes the file when the block ends. It closes it in a finally, so the file is closed even when the block raises an error.
with open() versus open() by hand: use with open() when the file is needed for one block of code. Open by hand only when you cannot put a with block around the code that uses the file. Then closing it is your job, also after an error.
Several context managers in one with statement
Separate the managers with commas. Each one gets its own as name, and the block can use them all. This copies every line from one file to another.
with open("lesson-menu.txt", "w", encoding="utf-8") as fixture: fixture.write("Soup\nPasta\n")with open("lesson-menu.txt", "r", encoding="utf-8") as source, open("lesson-copy.txt", "w", encoding="utf-8") as target: for line in source: target.write(line)with open("lesson-copy.txt", "r", encoding="utf-8") as source: print(source.read(), end="")The first two lines are setup: they make the file to copy. The middle with reads lesson-menu.txt through source and writes lesson-copy.txt through target. Each line from the loop still ends with \n, so target.write(line) keeps the lines apart. Both files are closed when the block ends. The last two lines read the copy back, so this prints Soup, then Pasta.
The managers are entered from left to right and cleaned up in reverse. tag() prints a start tag before its block and an end tag after it. It yields its name, so first is "a" and second is "b".
from contextlib import contextmanager@contextmanagerdef tag(name): print(f"<{name}>") yield name print(f"</{name}>")with tag("a") as first, tag("b") as second: print("inside", first, "and", second)This prints <a>, <b>, inside a and b, </b>, </a>. tag("a") is set up first and cleaned up last.
One with versus nested with blocks: one with with two managers is the same as a with for tag("a") with a nested with for tag("b") inside it. Use one statement when both managers belong to the same block. It saves a level of indentation.
The files in these examples live in the browser's temporary storage, and each example makes the files it reads. The examples leave out errors: tag() has no try and finally, so an error in its block would skip the end tags.
See also: How to Write to a Text File in Python, Python Read File, Python try finally.
Your turn
Use one with statement to open lesson-todo.txt for reading and lesson-shout.txt for writing. Write each line of the to-do list to lesson-shout.txt in capital letters.
FEED THE CAT WATER THE PLANTS
with open("lesson-todo.txt", "w", encoding="utf-8") as fixture: fixture.write("feed the cat\nwater the plants\n")# add one with statement that opens lesson-todo.txt to read and lesson-shout.txt to write,# then write each line in capital letters with upper()with open("lesson-shout.txt", "r", encoding="utf-8") as source: print(source.read(), end="")