Python language basics 87: reading from a text file
March 13, 2016 Leave a comment
Introduction
In the previous post we looked at context managers in with-blocks in Python. We said that context managers could be used with objects that require some type of opening and closing. We can open and close – or release – files. We can also open a HTTP channel to make a web request and then close it when we’re done. With-blocks makes our code more concise in that we don’t need to call the close() function anymore in code. Python will take care of that for us. In addition our code will be more robust since it can easily happen that the programmer forgets to call the close method on all open resources.
In this post we’ll look into reading text files. We’ll also see an example of multiple context managers.