Use with ... open() where appropriate instead of just open()

Use with ... open() where appropriate instead of just open(). Also made the open file handles a bit more consistent.