Popular recipes tagged "open" and "contextmanager"http://code.activestate.com/recipes/tags/open+contextmanager/popular/2017-03-13T13:27:50-07:00ActiveState Code RecipesContext Manager for an Arbitrary Number of Files in Python (Python)
2017-03-13T13:27:50-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580763-context-manager-for-an-arbitrary-number-of-files-i/
<p style="color: grey">
Python
recipe 580763
by <a href="/recipes/users/4182236/">Alfe</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/open/">open</a>).
Revision 2.
</p>
<p>The pattern using <code>with</code> together with <code>open()</code> to automatically close a file after leaving the context is well known. To open a fixed number you can simply nest these statements or use the comma notation. For having a context which represents an arbitrary number of open files you can use the <code>ExitStack</code> class, but only for Python 3.3+.</p>
<p>For other Python versions I'm using the following class which I named <code>Files</code>. The presented implementation is only for reading files (for keeping it clear). Extending it for having various file modes should not pose a problem.</p>