簡體   English   中英

打印到CSV會在每個迭代中打印標題

[英]Printing to CSV Prints Header Every Iteration

我試圖將來自arduino的數據寫入csv ia干凈,用戶友好的格式。 我想要的是將要輸入的數據打印出來,並提供一個標題,以便用戶查看列所代表的內容。 現在,當我將其打印到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM