Skip to content
Advertisement

Have each loop iteration create a new line of data in a file

I found and edited some code that records water flow data off of a flowmeter. I have managed to edit the script to run for only 5 mins and write to a file (I tried a .csv file but I am realizing this may not be entirely possible). However, when the script runs, the data file created just lists one “row” of recorded data. The while loop runs every 5 seconds for about 5 mins and provides a timestamp and a flow-rate reading, I’m trying to get the script to continuously record data. Here is the code:

JavaScript

I’ve included my “data writing” strings near the bottom in the while loop.

Advertisement

Answer

Opening the file with mode 'w' overwrites the whole file every time. So, just write the header at the beginning, and “append” later on:

JavaScript

This is only practical if you’re really only writing a row every now and then. If you’re writing more often, then you should just keep the file open and reuse the writer instance.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement