One problem here is that our f.close() call was never executed.
To fix that, we can insert a try … finally 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.