The key is to open the file handle and instanciate the CSV writer outside your loop, but write to it inside the loop:
import csv
import time
HEADER = ['LIGHT', 'VOLTAGE']
# ...
def processing_loop(csvfile):
csv_writer = csv.writer(csvfile)
csv_writer.writerow(HEADER)
# ...
while True:
light = ReadChannel(light)
voltage = ConvertVoltage(light)
csv_writer.writerow([light, voltage])
csvfile.flush()
time.sleep(5)
with open('results.csv', 'w') as csvfile:
processing_loop(csvfile)
For easier reading I factored out the loop into its own function that takes one argument, an open file handle that it can use to create the CSV writer with.
Also note the csvfile.flush()
- this is necessary if you want the data to be written to the file immediately upon every iteration. Otherwise it would only be writen once the file is closed (when you exit the with
block, i.e. terminate the script).