【问题标题】:How to check the fieldname before to write all values in csv file如何在将所有值写入csv文件之前检查字段名
【发布时间】:2018-04-12 21:37:10
【问题描述】:

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

【问题讨论】:

  • 我认为你的 lineValue 建设很奇怪......你能提供一个你以前拥有的和你期望的样本吗?对我来说,你的“如果”条件是错误的,因为你做的是分配而不是比较......
  • lineValue 是一个字符串,其中包含我从字典数据中获得的所有值{} 在这个问题中,您可以看到我如何对其进行编程的整个代码。 [链接] (stackoverflow.com/questions/47034977/…)
  • 我期望的是:我想在将值写入每列之前控制字段名。所以我将 100% 确定该值属于正确的键。我希望你明白我想做什么
  • 所以你想写'时间,价值'(来自你的代码),并且你想检查该值是否对应于正确的键?你能在你的csv文件中写一个你期望的样本吗,从哪个输入,我不清楚......
  • 是的。 Time, ValueSensor1,ValueSensor2,ValueSensor3... 问题是当其中一个传感器关闭时,我会在 LineValue 中丢失一个值,其中存储所有 Sensorvalues。所有值都将写入错误的键中。

标签: python csv dictionary for-loop field-names


【解决方案1】:

你可以试试这样的:

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

【讨论】:

  • 如何使用您的代码在阅读器中使用 for row 来检查写入字段名:您将获得整行
【解决方案2】:

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

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

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

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

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

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

对吗?

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

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

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'

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

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

编辑:从您的 cmets 升级

所以我知道您可能缺少已知传感器的值(已经在 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.

并在文件中替换它。

为此,您可以查看this post (我确实出于自己的目的测试了 Kiran 的答案,它运行良好,只需备份您的 CSV 文件,直到您的脚本正常运行以避免不必要的文件破坏)

【讨论】:

  • 非常感谢您非常详细的回答。问题是:我没有固定的 mySensors 列表。我自动获得传感器列表“例如,将直接检测到新的传感器 4 并将其添加到列表中”,这意味着当传感器 2 在 15.00 时丢失时,它的值也会丢失。但是每天 00:00 使用所有键“SensorsNames”创建的 CSV 文件仍然具有丢失的 Sensor2 的名称。这就是我认为的原因
  • 我无法从实际数据中检查丢失的 Sensor2 CSV 文件并读取我的传感器的标题并将其写入列表,然后将其与值进行比较。你怎么看?
  • 对不起,我的回答迟了。我刚刚修复了一些技术问题,现在我可以再次使用 Code。获取标题行的第一个函数给我一个存储的值,但不是带有 open(filename,'r') 作为 myFile 的标题行:readline = ""
  • 我怎样才能只获得包含所有传感器名称字段的标题行。我尝试使用 readline = myFile.read([0]) 但我不工作
  • 你真的有标题行吗?文件的前两行如何?
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2021-06-27
  • 2020-06-11
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多