File write method now closes file if error occurs