0

我想在csv文件中写一本字典。使用循环,我在文件for中写入字段名“键”“我的意思是列的标题”csv

期望的是:在写入我想要控制的值是否属于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()
4

2 回答 2

0

你可以尝试这样的事情:

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()
于 2017-10-31T16:29:32.657 回答
0

假设您的系统中有 3 个传感器,名称为 sensor1、sensor2、sensor3。假设这是一个众所周知的配置,您可以构建一个预期传感器列表来检查:

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

然后你有一个字典数据,你在其中存储你读取的传感器数据,即。

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

有时你有缺失值,假设传感器 2 关闭,那么你最终会得到

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

那正确吗 ?

然后使用您当前的代码,您会错过该值并在 CSV 的 sensor2 列中写入 sensor3 的值。

为避免这种情况,您可以遍历您的已知配置,即。名单。请注意,这仅在您具有众所周知且固定的传感器配置时才有效

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”

如果数据在第二个配置中(即缺少 sensor2),您将在文件中写入的行将是:

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

编辑:从您的评论升级

所以我知道您可能缺少已知传感器的值(已经在 CSV 文件中)、已知传感器的新值和新传感器的新值。

首先在 CSV 中获取标题行(应该看起来像'duration, sensor1, sensor2, ... sensorx')

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.

并在文件中替换它。

为此,您可以查看这篇文章 (我确实出于自己的目的测试了 Kiran 的答案,并且效果很好,只需备份您的 CSV 文件,直到您的脚本正常工作以避免不必要的文件破坏)

于 2017-11-03T14:36:07.597 回答