Ensure file handle is closed using with statement

This commit ensures the file is closed by using the with statement.