In CPython, the file object closes by itself as soon as the link count drops to 0, which is immediately after returning .readlines() . For other Python implementations, this may take a little longer, depending on the garbage collection algorithm used. The file, of course, will be closed no later than the program exit.
You really have to use the file object as a context manager and have a with statement on it:
with codecs.open(somefile, 'r','utf8') as reader: lines = reader.readlines()
As soon as a block of code that recedes under the with statement exits (whether with an exception, a return , continue or break ) or simply because all the code in the completed block is executed), the reader file object will be closed.
Bonus tip: file objects are iterable, so the following also works:
with codecs.open(somefile, 'r','utf8') as reader: lines = list(reader)
for the same result.
source share