在使用 python 将值写入 csv 文件之前将值与字段名进行比较

compare values with fieldnames before writing it in csv file using python

在我将其存储在 csv 文件中以检查正确的列之前,我使用此代码将值与其附属字段名进行比较,因为每次我重新启动机器时,字典中传感器的顺序都会更改自动地。这就是为什么我必须在将值存储到 csv 文件之前控制它在 dict 中的位置,否则我会得到一个混乱的 csv 文件,如下面的示例,其中提供的值温度为 1000 [°C],亮度为 10 [lux]

import csv
from datetime import datetime
import os
import time
from collections import OrderedDict
from time import sleep


Datum = time.strftime("%Y-%m-%d")
Time = datetime.now().replace(microsecond=0).isoformat()

data = {'Stecker Energy': '2.37', 'Stromzaehler Strom L1 [A]': '0.0', '1OG Ultraviolet': '0.0','Stecker EG  Energie [kWh]': '4.3'}

filename = Datum + 'SOF.csv'
if not os.path.isfile(filename):
    outfile = open(filename, "w")
    lineKey = ""
    for x in data.keys():
        lineKey+= x + ","
    lineKey = 'Time '+ "," + lineKey[:-1]+"\n" # Delete last character and add new line
    outfile = open(filename, "a")
    outfile.write(lineKey)
    outfile.close()

#check first line of  fieldnames 
with open(filename,'r') as myFile:
    reader = csv.DictReader(myFile)
    fieldnames = reader.fieldnames
    myFile.close()
#Compare the values with their  keys (fieldnames)
with open(filename,'a') as outfile:
    lineValue = ""
    for sensor, value  in data.items():
        if sensor in data.items()==sensor in fieldnames:
            v = data[sensor]
            print("v", v)
            lineValue+= str(v) + "," 
    lineValue = Time + "," + lineValue[:-1] + "\n"
    print(lineValue)
    outfile.write(lineValue)
    outfile.close()

问题是当我检查 CSV 文件时,我发现值写在错误的列中,这意味着 Examlpe 的字段名称错误:

CSV 文件中的此问题示例

CSV 文本示例

时间,Stromzaehler Strom L1 [A],Stecker Energy,1OG 紫外线,Stecker EG Energie [kWh] 2017-11-21T17:56:10,2.37,0.0,0.0,4.3 2017-11-21T17:56:26,4.3,0.0,0.0,2.37 2017-11-21T17:56:28,0,0.0,2.37,4.3 2017-11-21T17:56:30,0,2.37,0.0,4.3

data = {'Stecker Energy': '', 'Stromzaehler Strom L1 [A]': '', '1OG Ultraviolet': '','Stecker EG  Energie [kWh]': ''}
for sensor, value  in data.items():
    if sensor in data.items()==sensor in fieldnames:
        v = data[sensor]
        print("v", v)
        lineValue+= str(v) + "," 

我觉得这不对。如果您只想遍历所有字段名("Time" 除外)并在 data 中添加与这些字段对应的值,同时还为 "n/a" 中不存在的值添加 "n/a" 16=],那么我建议这样做:

with open(filename,'a') as outfile:
    lineValue = ""
    for fieldname in fieldnames[1:]: #skip the first one, since that's Time, which we have a custom value for already.
        v = data.get(fieldname, "n/a")
        lineValue += str(v) + ","
    lineValue = Time + "," + lineValue[:-1] + "\n"
    print(lineValue)
    outfile.write(lineValue)
    outfile.close()

额外建议:手动在值之间添加逗号是一种容易出错的方法。如果可能,请使用 DictWriter,它会为您解决大部分格式问题。

with open(filename,'a') as outfile:
    writer = csv.DictWriter(outfile, fieldnames)
    row = {}    
    for fieldname in fieldnames: #no need to skip Time here, we'll just overwrite it later.
        row[fieldname] = data.get(fieldname, "n/a")
    row["Time "] = Time
    writer.writerow(row)

如果您坚持不这样做,至少将值存储在一个列表中,最后 join 一次:

with open(filename,'a') as outfile:
    values = [Time]
    for fieldname in fieldnames[1:]:
        v = data.get(fieldname, "n/a")
        values.append(str(v))
    outfile.write(",".join(values) + "\n")

额外奖励建议:如果这些解决方案在您不想要的行之间添加了额外的空行,您可以使用 newline="" 参数打开文件(如果使用 Python 3):

with open(filename,'a', newline="") as outfile:

... 或者以二进制模式打开文件(如果使用 Python 2):

with open(filename,'ab') as outfile: