One thing you could do is to keep everything in memory and only write at the very end. There are only two reasons not to do that: The files are too big (unlikely these days with text); or you want backup in case of a crash. The latter is easily fixed by writing the entire file periodically in the background.
↧