reading from a text file

Tim Golden mail at timgolden.me.uk
Mon Nov 30 13:34:46 EST 2009


inhahe wrote:
> i don't understand the point of using 'with'
> but i don't understand what 'with' does at all
> i've tried to understand it a few times
> anyway here:
> 
> import random
> result = random.choice(open("c:\\test.txt").readlines())


Yep. That'll do the trick. The point of "with" is that,
while in CPython, an open file will be closed as soon
as it is out of scope -- in this case, after that line --
in other implementations of Python, this may not be so.
Good practice suggests using with (or try/finally) which
ensures that the file is closed, regardless of the implementation.

For a quick example it's not always easy to know whether
to include this kind of detail, but a with: block adds
very little noise and will save you from being caught out
somewhere, someday.

http://www.python.org/doc/current/whatsnew/2.6.html#pep-343-the-with-statement

TJG



More information about the Python-list mailing list