Ensure file handle is closed using with statement (core.py)

This change also ensures the file handle is closed by using the with statement.