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

Python 打印到CSV会在每次迭代中打印标题,python,python-3.x,csv,Python,Python 3.x,Csv,我试图将来自arduino的数据以干净、用户友好的格式写入csv I。我想要的是在数据输入时打印出来,并给它一个标题,这样用户就可以看到列所代表的内容。现在,当我将其打印到csv时,每次迭代都会得到标题。我将得到的是: Newtons # Newtons # 我尝试过使用csv.writer和csv.DictWriter,两者都得到了相同的结果。 在上下文中,我让arduino从传感器获取数据,然后python根据传感器读数告诉arduino应该做什么,我想保存传感器读数以供分析 Python

我试图将来自arduino的数据以干净、用户友好的格式写入csv I。我想要的是在数据输入时打印出来,并给它一个标题,这样用户就可以看到列所代表的内容。现在,当我将其打印到csv时,每次迭代都会得到标题。我将得到的是:

Newtons
#
Newtons
#
我尝试过使用csv.writer和csv.DictWriter,两者都得到了相同的结果。 在上下文中,我让arduino从传感器获取数据,然后python根据传感器读数告诉arduino应该做什么,我想保存传感器读数以供分析

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]})

问题是输出文件的定义和
writeheader()
的调用都在循环中

这应该起作用:

#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

outfileWrite
的定义和对
outfileWrite.writeheader()的调用移出循环。