There is a really great answer about writing/reading/copying for files here: https://stackoverflow.com/a/28129677/15096247
In your case, it is a bit of work to adapt it (split on newlines, basically), but it might be worth it. I use it quite often.