reading from a text file
mail at timgolden.me.uk
Mon Nov 30 19:34:46 CET 2009
> 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
More information about the Python-list