I've come across some code that iterates through lines in a file like so:
for line in open(filename, 'r'):
do_all_the_things()
Is that a more Pythonic version of something like:
with open(filename, 'r') as f:
for line in f:
do_all_the_things()
It uses less indentation levels, so it looks nicer, but is it the same? From what I know, with
basically adds a finally: f.close()
or something to that effect to ensure after leaving the block the object is cleaned up. When the first for
loop ends (or is cut short with a break
perhaps) and the variable goes out-of-scope does the same thing happen? Can I take my cue from the first bit of code and save myself some keystrokes, or rather, should I fix it?