You can place the "write to file" part of the code within the loop where you obtain the data. If you add the newly acquired data, simply select "append to file".
So here's an idea of the steps:
1. create the file where you want to store the data.
2. inside the loop where the acquisition takes place, write to the file. Use "append to file " option.
3. Outside the acquisition loop, close the file. Make sure you can clse the file even if an error was detected.
Run it and see if your data was kept.
JLV