如何在CSV文件中写入所有值之前检查字段名

jum4pzuy  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(116)

我想在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()
xxls0lw8

xxls0lw81#

你可以试试这样的方法:

import csv

ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter='', quotechar='"', quoting=csv.QUOTE_ALL)

for row in reader:
    writer.writerow(row)

ofile.close()
7qhs6swi

7qhs6swi2#

假设您的系统中有3个传感器,分别为sensor 1、sensor 2和sensor 3。假设这是一个众所周知的配置,您可以构建一个要检查的预期传感器列表:

mySensors=['sensor1', 'sensor2', 'sensor3']

然后你有一个字典数据,你存储的传感器数据,你读,即.

data={'sensor1':value1;'sensor2':value2;'sensor3':value3}

有时候,如果sensor 2为OFF,则会出现缺失值,结果为

data={'sensor1':value1;'sensor3':value3}

对吗?
然后,使用当前代码,您会错过该值,并将sensor 3的值写入CSV的sensor 2列中。
为了避免这种情况,您可以循环使用您已知的配置,即。请注意,只有当您具有已知且固定传感器配置时,此选项才有效

with open(filename,'a') as outfile:
    lineValue = ""
    for component in mySensors:
        # check that the sensor is in the data read
        if component not in data:
            # the sensor has not been read, set a neutral value
            lineValue+= 'n/a' + ","
        else:
            v = data[component]
            lineValue+= str(v) + ","  # I cast value for my test, your value is probably already in correct format
        #for k,v in data.items():
        #    if k[]=v[]: => Can you explain that comparison, please ? 
        #        lineValue+= v + ","
    lineValue = Time + "," + lineValue[:-1] + "\n" 
    outfile.write(lineValue)

这应该可以处理值转移。您可以设置任何中性值而不是'n/a'
如果数据处于第二种配置(即缺少sensor 2),则您将在文件中写入的行将是:

'Time,5,n/a,20\n'

编辑:从您的评论中升级

因此,我理解您可能有已知传感器的缺失值(已在CSV文件中)、已知传感器的新值和新传感器的新值。
首先在CSV中获取标题行(应该类似于“duration,sensor 1,sensor 2,...传感器x’)

with open(filename,'r') as myFile:
    readline = ""
    # parse file until you hit the header line
    for line in myFile:
        readline = myFile.read()
        if readline != "":
            break

从这里,得到列表:

mySensors = readline.split(',')
# should give ['duration','sensor1','sensor2', etc.] => remove 'duration' column header

然后解析这个sensorList。因此,如果你从列表中点击一个没有值的传感器,它会写'n/a'
要添加可能在两次CSV文件更新之间出现的新传感器,请在第一个循环之后添加第二个“for”循环:

# then check if there are new sensors that appeared and that are not in current set of sensors
header_update = False # to check if header has to be updated

for sensor, value in data.items():
    if sensor not in mySensors:
        # new sensor to add 
        lineValue+=str(value)
        # add the new sensor id in the header list
        mySensors.append(sensor)
        if not header_update : header_update = True
        
# terminate the line to write
lineValue = Time + "," + lineValue[:-1] + "\n"

在那之后,问题是将新的传感器添加到您的标题行中,因此您必须构建新的标题行

# new header line to replace the previous header
if header_update:
    new_header = "duration," # assuming that your first column header is 'duration'
    new_header += ','_join.mySensors
# this will build a new header line like duration,sensor1,sensor2,..., sensorx, newsensor1, etc.

并将其替换到文件中。
要做到这一点,你可以看看this post(我确实测试了Kiran的答案,它工作得很好,只是备份你的CSV文件直到你的脚本正常工作,以避免不必要的文件破坏)

相关问题