Is there a need to close files that have no reference to them?

The pythonic way to deal with this is to use the with context manager:

with open(from_file) as in_file, open(to_file, 'w') as out_file:
    indata = in_file.read()
    out_file.write(indata)

Used with files like this, with will ensure all the necessary cleanup is done for you, even if read() or write() throw errors.

Leave a Comment