Use the with statement where applicable

This change replaces try..finally or open().read() with constructs using the with statement so that the code is easier to read and files are closed everywhere. This also seems to fix a couple of issues with PyPy.