0

Right now, the print line reads a voltage from my sensor and prints it on the screen every 50ms. I want to output this to a CSV file when the code gets interrupted. I read other tutorials on how to output to a CSV file when the output is already determined, but I cannot figure out how to write to a csv file when I need to read live voltage.

This is the answer that I cannot manage to adapt to my code: writing print output to csv file

from ABE_ADCDACPi import ADCDACPi
import time

adcdac = ADCDACPi()
adcdac.set_adc_refvoltage(3.3)

while True:
    print (adcdac.read_adc_voltage(1, 0))
    time.sleep(0.05)

EDIT: This is not the same using VBA to merge CSV files. I am writing from a sensor to an ADC to a microcontroller to RAM to CSV.

sorin
  • 33
  • 8
  • What precisely do you mean by *gets interrupted* here? How many values do you want per row in your final CSV output? – torek Oct 20 '18 at 16:17
  • I would press a button and the code would stop and the csv gets saved. 1 value per row. – sorin Oct 20 '18 at 16:30
  • 1
    For one value per row, just call the write-a-row function on each trip through the loop, at the same point that you call `print`. – torek Oct 20 '18 at 16:46
  • Possible duplicate of [CSVWriter not saving data to file the moment I write it](https://stackoverflow.com/questions/3976711/csvwriter-not-saving-data-to-file-the-moment-i-write-it) – ivan_pozdeev Oct 20 '18 at 18:36

1 Answers1

1

Multiple solutions :

  • Redirect output to file

    python yourscript.py > log.txt
    
  • Print to file

    with open('log.txt', 'a') as f:
        print (adcdac.read_adc_voltage(1, 0), file=f)
    
  • Use logging :

    import logging
    logging.basicConfig(filename='log.txt',level=logging.INFO)
    while True:
        logging.info(adcdac.read_adc_voltage(1, 0))
        time.sleep(0.05)
    
Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
  • Will this allow me to view the CSV in Windows while my spider is still scraping and outputting? Currently, if I keep the CSV file open, I run into a `permission denied` error – oldboy Oct 27 '18 at 21:14
  • Hello @Anthony, this has nothing to do with python. You probably used excel which sets the file as read only once opened. Maybe there is an option within excel to change this behavior. If not, i recommand you to try an other software to read the file (notepad++ does not set the read only flag for example) – Corentin Limier Oct 28 '18 at 16:49
  • oh shit i didnt even realize `csv` files were readable by other programs!! thanks – oldboy Oct 28 '18 at 22:07