Domanda

I'm trying to log some data with python and I want it to save a datapoint into a text file at every iteration.

So currently I have

while true:
    light = ReadChannel(light)
    voltage =  ConvertVoltage(light)
    print(light, voltage)
    time.delay(5)

So the print would ideally become a write command. I've checked the site but nothing seems to support a while loop write command (as it opens and closes it constantly).

È stato utile?

Soluzione

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).

Altri suggerimenti

I have no idea what you mean by saying that nothing supports writing inside a loop. That is of course the usual way to do things: you open the file outside the loop, write to it consecutively inside the loop, then close it afterwards.

with open('myfile.csv', 'w') as f
    writer = csv.writer(f)
    while True:
        light = whatever
        voltage = whatever
        writer.writerow([light, voltage])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top