简体   繁体   English

打印到CSV会在每个迭代中打印标题

[英]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. 我试图将来自arduino的数据写入csv ia干净,用户友好的格式。 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. 现在,当我将其打印到csv时,每次迭代都获得标头。 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. 我尝试使用csv.writer和csv.DictWriter并产生相同的结果。 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. 对于上下文,我有一个arduino从传感器获取数据,然后python然后根据传感器的读数告诉arduino做什么,并且我想保存此传感器读数以进行分析。

Python Code Python代码

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 问题是您对输出文件的定义和对writeheader()的调用在循环中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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