How do I close a file if i didn't initialize it?

file, io, python

Solution

In CPython, the file object will close on its own once the reference count drops to 0, which is right after `.readlines()` returns. For other Python implementations it may take a little longer depending on the garbage collection algorithm used. The file is certainly going to be closed no later than program exit.

You should really use the file object as a context manager and have the `with` statement call close on it:

with codecs.open(somefile, 'r','utf8') as reader:
    lines = reader.readlines()

As soon as the block of code indented under the `with` statement exits (be it with an exception, a `return`, `continue` or `break` statement, or simply because all code in the block finished executing), the `reader` file object will be closed.

Bonus tip: file objects are iterables, so the following also works:

with codecs.open(somefile, 'r','utf8') as reader:
    lines = list(reader)

for the exact same result.

Problem

If i've done the following: ``` import codecs lines = codecs.open(somefile, 'r','utf8').readlines() ``` Is there a way to close the file that i've not initialized? If so, how? Normally, i could have done: ``` import codecs reader = codecs.open(somefile, 'r','utf8') lines = reader.readlines() reader.close() ```

Original source