3 ms·
I don't get it. Can someone explain to me how this is different or better than: infile = open('site.log'); outfile = open('err.log', 'w') for line in infil
by AceJohnny2 14y ago
I don't get it. Can someone explain to me how this is different or better than:
infile = open('site.log'); outfile = open('err.log', 'w')
for line in infile:
if 'ERROR' in line:
outfile.write(line)
infile.close(); outfile.close()
Sure, you're saving a line with the files being automatically closed at the end of your scope, but hardly "MIND == BLOWN".
What am I missing?
- Maascamp 14y agoError handling.
- endlessvoid94 14y agoelegance?
- baddox 14y ago"MIND == BLOWN" is a hyperbole in almost every context, but the `with` statement is just cleaner code with fewer chances to screw up (e.g. by forgetting to close).
- deleted 14y ago[deleted]
- graue 14y agoYou're missing that if an exception gets thrown, the files are still guaranteed to be closed as soon as you exit that 'with' block. Imagine you open 'infile', but then opening 'outfile' fails. To prevent a resource leak, now you need to close 'infile'. The linked code guarantees this. Likewise if there is any error which aborts the copying, both files will get closed and you don't have to worry so much about corner cases. See this for more: http://effbot.org/zone/python-with-statement.htm http://effbot.org/zone/python-with-statement.htm
- nnq 14y agoIn a more complex application, an exception might be thrown before the last line that closes the file (and caught god knows where or not at all), so the files may not be closed... then again, if you actually try to catch the exceptions you get an extra level of indentation by using `with`. More... "philosophy" here: http://stackoverflow.com/questions/11373502/zen-of-python-vs-with-statement-philosophical-pondering http://stackoverflow.com/questions/11373502/zen-of-python-vs...
- AceJohnny2 14y agoAh, so 'with' is a clearer syntax for exception handling, that's what I was missing. Thanks to you, masklinn and graue for clearing that up.
- nnq 14y agoGlad it helped you, but I wouldn't say "a clearer syntax for exception handling" really... more like a "way to ensure your code always works without having to actually think about exceptions". (Wrong as it may seem, I try to imagine I'm using "let" in a Lisp and then I instantly start to love the "with" syntax, although it's not a necessary part of Python :) )
- masklinn 14y ago> Sure, you're saving a line with the files being automatically closed at the end of your scope That's actually pretty significant if you're, say, using Pypy or IronPython, otherwise you're leaking handlers if you've got an error raised. But he was actually comparing the code to: with open('site.log') as infile: with open('err.log', 'w') as outfile: # code . MIND=BLOWN is tongue-in-cheek. Hopefully. Then again, he's commenting on a 2 or 3 years old version of python so...