Factored out try-finally blocks for file IO, using with statement