The with-blocks

Up to now our examples have all followed a pattern: open() a file, work with the file, close() the file. The close() is important because it informs the underlying operating system that you're done working with the file. If you don't close a file when you're done with it, it's possible to lose data. There may be pending writes buffered up which might not get written completely. Furthermore, if you're opening lots of files, your system may run out of resources. Since we always want to pair every open() with a close(), we would like a mechanism that enforces the relationship even if we forget.

This need for resource clean up is common enough that Python implements a specific control flow structure called with-blocks to support it. The with-blocks can be used with any object that supports the context-manager protocol, which includes the file-objects returned by open(). Exploiting the fact the the file object is a context manager, our read_series() function can become simply:

def read_series(filename):
with open(filename, mode='rt', encoding='utf-8') as f:
return [int(line.strip()) for line in f]

We no longer need to call close() explicitly because the with construct will call it for us when execution exits the block, no matter how we exit the block.

Now we can go back and modify our Recaman series writing program to use a with-block, too, again removing the need for the explicit close():

def write_sequence(filename, num):
"""Write Recaman's sequence to a text file."""
with open(filename, mode='wt', encoding='utf-8') as f:
f.writelines("{0} ".format(r)
for r in islice(sequence(), num + 1))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset