
mail at timgolden
Nov 30, 2009, 10:34 AM
Post #7 of 7
(288 views)
Permalink
|
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 -- http://mail.python.org/mailman/listinfo/python-list
|