python - 打印到 CSV 打印标题每次迭代
问题描述
我正在尝试将来自 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
推荐阅读
- java - GlobalKTable - StreamsException:遇到与任何全局状态存储无关的主题分区
- android - 如何在 Firebase 实时数据库中搜索类似数组的数据?
- r - 如何根据数据表中的特定行按组计算比率
- android - 如何使项目角夹在微调器弹出窗口内?
- docker - 如何模拟 Docker 容器失去互联网连接?
- unity3d - 可寻址对象:保存/加载到文件
- c# - Reactive Extensions C# - 如何在执行(相对)长时间运行的订阅逻辑时跳过消息
- azure-data-explorer - Kusto如何在一组每日记录中选择最新的具有相同id的记录
- concurrency - VHDL 断言 - 并发语句
- java - 如何降低此代码的复杂性?