Use with statement to close file handle

This applies the same change as in commit 07cfa81da31bf1f9903caaade52faefa26cc73ca (use with statement to ensure the file handle is closed).