Managing resources with finally

One problem here is that our f.close() call was never executed.

To fix that, we can insert a tryfinally block:

def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
finally:
f.close()
return series

Now the file will always be closed, even in the presence of exceptions. Making this change opens up the opportunity for another refactoring: we can replace the for-loop with a list comprehension and return this list directly:

def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [ int(line.strip()) for line in f ]
finally:
f.close()

Even in this situation close() will still be called; the finally block is called no matter how the try block is exited.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset