Ensure file handle is closed using with statement

This changes ensures that the opened file is also closed.