我想在csv
文件中写一个字典。使用for
循环,我在csv
文件中写入字段名“keys”“i mean titles of columns”
所需:如果值属于csv
文件中的右字段,则在写入我要控制的值之前使用。我尝试了类似的东西,但当我改变dict
的顺序。我在错误的字段中得到值
lineValue = ""
for k,v in data.items():
if k[]=v[]:
lineValue+= v + ","
lineValue = Time + "," + lineValue[:-1] + "\n"
outfile = open(filename, "a")
outfile.write(lineValue)
outfile.close()
2条答案
按热度按时间xxls0lw81#
你可以试试这样的方法:
7qhs6swi2#
假设您的系统中有3个传感器,分别为sensor 1、sensor 2和sensor 3。假设这是一个众所周知的配置,您可以构建一个要检查的预期传感器列表:
然后你有一个字典数据,你存储的传感器数据,你读,即.
有时候,如果sensor 2为OFF,则会出现缺失值,结果为
对吗?
然后,使用当前代码,您会错过该值,并将sensor 3的值写入CSV的sensor 2列中。
为了避免这种情况,您可以循环使用您已知的配置,即。请注意,只有当您具有已知且固定传感器配置时,此选项才有效
这应该可以处理值转移。您可以设置任何中性值而不是'n/a'
如果数据处于第二种配置(即缺少sensor 2),则您将在文件中写入的行将是:
编辑:从您的评论中升级
因此,我理解您可能有已知传感器的缺失值(已在CSV文件中)、已知传感器的新值和新传感器的新值。
首先在CSV中获取标题行(应该类似于“duration,sensor 1,sensor 2,...传感器x’)
从这里,得到列表:
然后解析这个sensorList。因此,如果你从列表中点击一个没有值的传感器,它会写'n/a'
要添加可能在两次CSV文件更新之间出现的新传感器,请在第一个循环之后添加第二个“for”循环:
在那之后,问题是将新的传感器添加到您的标题行中,因此您必须构建新的标题行
并将其替换到文件中。
要做到这一点,你可以看看this post(我确实测试了Kiran的答案,它工作得很好,只是备份你的CSV文件直到你的脚本正常工作,以避免不必要的文件破坏)