将值与字段名称进行比较,然后使用python将其写入csv文件 [英] compare values with fieldnames before writing it in csv file using python

查看:158
本文介绍了将值与字段名称进行比较,然后使用python将其写入csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using this code to compare value with their affiliated fieldnames before i store it in the csv-file to check the right column, because everytime when i reboot my machine the order of sensors in the dictionary will be changed autamatically. this why i have to control the the position of value in dict before i store it in csv file, otherwise i will get a mess csv file like the example bellow which provide the value temperatur is 1000 [°C] the luminisity 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的字段名错误:

The problem is when i check CSV-file i found that value are written in the wrong column which means wrong fieldnames for Examlpe:

CSV文件中此问题的示例

CSV文本示例

时间,Stromzaehler Strom L1 [A],Stecker能量,1OG紫外线,Stecker EG能量[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

Time ,Stromzaehler Strom L1 [A],Stecker Energy,1OG Ultraviolet,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) + "," 

这对我来说并不正确.如果您只想遍历所有字段名(时间"以外的字段)并在data中添加与这些字段相对应的值,同时还为"data"中不存在的值添加"n/a",那么我建议这样做:

This doesn't look right to me. If you just want to iterate through all the fieldnames (other than "Time") and add the values in data that correspond to those fields, while also putting "n/a" for values not present in data, then I suggest doing:

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,它可以为您解决大多数格式问题.


Bonus suggestion: Adding commas between values manually is an error-prone approach. If possible, use DictWriter, which takes care of most formatting problems for you.

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:

If you insist on not doing that, at least store the values in a list, which you join once at the end:

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):


Bonus bonus suggestion: if these solutions add extra empty lines between rows that you don't want, you open the file with the newline="" argument (if using Python 3):

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

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

... Or open the file in binary mode (if using Python 2):

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

这篇关于将值与字段名称进行比较,然后使用python将其写入csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆