简体   繁体   中英

Printing to CSV Prints Header Every Iteration

I am trying to get my data that is coming in from an arduino to be written to a csv ia clean, user friendly format. What I want is my data to be printed as it came in and given a header that way the user can see what the columns represent. Right now when I print it to a csv I get the header every iteration. What will happen is I get is:

Newtons
#
Newtons
#

I have tried using the csv.writer and the csv.DictWriter and both yield the same result. For context I have an arduino acquiring data from a sensor, and then python is then telling the arduino what to do based on the sensor reading and I want to save this sensor reading for analysis.

Python Code

import serial
import csv
import time
from time import localtime, strftime
import warnings
import serial.tools.list_ports


__author__ = 'Matt Munn'
arduino_ports = [
    p.device
    for p in serial.tools.list_ports.comports()
    if 'Arduino' in p.description
]
if not arduino_ports:
    raise IOError("No Arduino found - is it plugged in? If so, restart computer.")
if len(arduino_ports) > 1:
    warnings.warn('Multiple Arduinos found - using the first')

Arduino = serial.Serial(arduino_ports[0],9600,timeout=1)
time.sleep(2)


start_time=time.time()

Force = []
Actuator_Signal=[]
numPoints = 10
ForceList = [0]*numPoints
AvgForce = 0

#This creates the unique file for saving test result data.

outputFileName = "Cycle_Pull_Test_#.csv"
outputFileName = outputFileName.replace("#", strftime("%Y-%m-%d_%H %M %S", localtime()))

with open(outputFileName, 'w',newline='') as outfile:


    #This takes the data from the arduino and interprits it.

    while True:
        while (Arduino.inWaiting()==0):
            pass
        try:

            data = Arduino.readline()
            dataarray = data.decode().rstrip().split(',')

            for i in range(0,numPoints):
                Force = round(float(dataarray[0]),3)
                ForceList[i] = Force
                AvgForce = round((sum(ForceList)/numPoints),3)
                print (AvgForce) 
         #This Controls the actuators direction based on the force input on the loadcell.
            if AvgForce >50:
                Arduino.write(b'd')
            else: 
                Arduino.write(b'u')
        except (KeyboardInterrupt, SystemExit,IndexError,ValueError):
            pass

        #This writes the data from the loadcell to a csv file for future use.
        HeaderNames = ['Newtons']
        outfileWrite = csv.DictWriter(outfile, fieldnames = HeaderNames)
        outfileWrite.writeheader() 
        outfileWrite.writerow({'Newtons' : [AvgForce]})

The problem is that your definition of the output file and the call of writeheader() is in the loop

This should work:

#This takes the data from the arduino and interprits it.

outfileWrite = csv.DictWriter(outfile, fieldnames = HeaderNames)
outfileWrite.writeheader() 

while True:
    # Rest of the while loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM