more memory efficient file writing